home *** CD-ROM | disk | FTP | other *** search
/ Chip 2011 November / CHIP_2011_11.iso / Programy / Narzedzia / WebsiteX5 / wsx5_free.exe / {app} / Res / x5engine.php < prev   
PHP Script  |  2011-08-25  |  89KB  |  2,468 lines

  1. <?php
  2. /**
  3.  * This file contains all the classes used by the PHP code created by WebSite X5
  4.  * @author Incomedia Srl (http://www.incomedia.eu)
  5.  * @version 1.0
  6.  */
  7.  
  8. @session_start();
  9.  
  10. $imSettings = Array();
  11. $l10n = Array();
  12. $phpError = false;
  13.  
  14. @include("imemail.inc.php");        // Email class - Static
  15. @include("x5settings.php");            // Basic settings - Dynamically created by WebSite X5
  16. @include("blog.inc.php");            // Blog data - Dynamically created by WebSite X5
  17. @include("cart.inc.php");            // E-commerce cart data - Dynamically created by WebSite X5
  18. @include("access.inc.php");            // Private area data - Dynamically created by WebSite X5
  19. @include("l10n.php");                // Localizations - Dynamically created by WebSite X5
  20. @include("search.inc.php");            // Search engine data - Dynamically created by WebSite X5
  21.  
  22. /**
  23.  * Contains the methods used to format and send emails
  24.  * @access public
  25.  */
  26. class imSendEmail {
  27.  
  28.     /**
  29.      * Send the E-commerce cart order/email
  30.      * @access public
  31.      * @param post The data sent by the form of the e-commerce cart at step 4 (array)
  32.      */
  33.     function sendCartEmail($post_data) {
  34.  
  35.         global $imSettings;
  36.         global $l10n;
  37.  
  38.         $separationLine = "<tr><td colspan=\"2\" style=\"margin: 10px 0; height: 10px; font-size: 0.1px; border-bottom: 1px solid " . $imSettings['email']['email_background'] . ";\"> </td></tr>\n";
  39.         $PayMsg = $imSettings['cart']['confirmationEmail'];
  40.         $ownerEmail = $imSettings['cart']['owner_email'];
  41.         $imOpt = 0;
  42.         $imVat = 0;
  43.         $imOrderNo = $post_data["order_no"];
  44.         $imUserData = $post_data["form"];
  45.         $imShippingDataTxt = "";
  46.         $imShippingDataHtml = "";
  47.         $imUserDataTxt = "";
  48.         $imUserDataHtml = "";
  49.         $imUserDataCSVH = "";
  50.         $imUserDataCSV = "";
  51.  
  52.         $i = 0;
  53.         if(is_array($imUserData)) {
  54.             foreach($imUserData as $key => $value) {
  55.                 // Is it an email?
  56.                 if (preg_match('/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\@([a-z0-9])' . '(([a-z0-9-])*([a-z0-9]))+' . '(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i', $value['imValue'])) {
  57.                     $f = "<td><b>" . str_replace(array("\\'", '\\"'), array("'", '"'), $value['name']) . ":</b></td><td><a href=\"mailto:" . $value['imValue'] . "\">". $value['imValue'] . "</a></td>";
  58.                 } else if (preg_match('/^http[s]?:\/\/[a-zA-Z0-9\.\-]{2,}\.[a-zA-Z]{2,}/', $value['imValue'])) {
  59.                     // Is it an URL?
  60.                     $f = "<td><b>" . str_replace(array("\\'", '\\"'), array("'", '"'), $value['name']) . ":</b></td><td><a href=\"" . $value['imValue'] . "\">". $value['imValue'] . "</a></td>";
  61.                 } else {
  62.                     $f = "<td><b>" . str_replace(array("\\'", '\\"'), array("'", '"'), $value['name']) . ":</b></td><td>" . str_replace(array("\\'", '\\"'), array("'", '"'), $value['imValue']) . "</td>";
  63.                 }
  64.                 
  65.                 if (substr($key, -strlen("_shipping")) == "_shipping") {
  66.                     $imShippingDataTxt .= $value['name'] . ": " . $value['imValue'] . "\n";
  67.                     $imShippingDataHtml .= "\n\t\t\t\t<tr" . ($i%2 ? " bgcolor=\"" . $imSettings['email']['body_background_odd'] . "\"" : "") . ">" . $f . "</tr>";
  68.                     $imShippingDataCSVH[] = $value['name'];
  69.                     $imShippingDataCSV[] = $value['imValue'];
  70.                 } else {
  71.                     $imUserDataTxt .= $value['name'] . ": " . $value['imValue'] . "\n";
  72.                     $imUserDataHtml .= "\n\t\t\t\t<tr" . ($i%2 ? " bgcolor=\"" . $imSettings['email']['body_background_odd'] . "\"" : "") . ">" . $f . "</tr>";
  73.                     $imUserDataCSVH[] = $value['name'];
  74.                     $imUserDataCSV[] = $value['imValue'];
  75.                 }
  76.                 $i++;
  77.             }
  78.             if ($imUserDataHtml != "")
  79.                 $imUserDataHtml = "<table width=\"100%\" style=\"font: inherit;\">" . $imUserDataHtml . "</table>";
  80.  
  81.             if ($imShippingDataHtml != "")
  82.                 $imShippingDataHtml = "<table width=\"100%\" style=\"font: inherit;\">" . $imShippingDataHtml . "</table>";
  83.         }
  84.         $imUserDataCSV = @implode(";",$imUserDataCSVH) . "\n" . @implode(";",$imUserDataCSV);
  85.         $imShippingDataCSV = @implode(";",$imShippingDataCSVH) . "\n" . @implode(";",$imShippingDataCSV);
  86.  
  87.         $imOrderData = $post_data["products"];
  88.         $imOrderDataTxt = "";
  89.         $imOrderDataHTML = "";
  90.         $imOrderDataCSV = "";
  91.         $i = 0;
  92.         if(is_array($imOrderData)) {
  93.            foreach($imOrderData as $p) {
  94.               if($p["option"] != "null")
  95.                 $imOpt = 1;
  96.               if ($p["vat"] != "null" && $p["vat"] != 0)
  97.                 $imVat = 1;
  98.            }
  99.            $colspan = 3 + $imOpt + $imVat;
  100.            $imOrderDataHTML = "<table cellpadding=\"5\" width=\"100%\" style=\"font: inherit; border-collapse: collapse;\"><tr bgcolor=\"" . $imSettings['email']['body_background_odd'] . "\"><td style=\"border: 1px solid " . $imSettings['email']['body_background_border'] . ";\"><b>" . $l10n["cart_name"] . "</b></td>" . ($imOpt ? "<td style=\"border: 1px solid " . $imSettings['email']['body_background_border'] . ";\"><b>" . $l10n["product_option"] . "</b></td>" : "") . "<td style=\"border: 1px solid " . $imSettings['email']['body_background_border'] . ";\"><b>" . $l10n["cart_qty"] . "</b></td><td style=\"border: 1px solid " . $imSettings['email']['body_background_border'] . ";\"><b>" . $l10n["cart_price"] . "</b></td>" . ($imVat ? "<td style=\"border: 1px solid " . $imSettings['email']['body_background_border'] . ";\"><b>" . $l10n["cart_VAT"] ."</b></td>" : "") . "<td  style=\"border: 1px solid " . $imSettings['email']['body_background_border'] . "; width: " . $priceFieldWidth . "\"><b>" . $l10n["cart_subtot"] . "</b></td></tr>\n";
  101.            $imOrderDataCSV = $l10n["cart_name"] . ";" . $l10n["cart_descr"] . ";" . ($imOpt ? $l10n["product_option"] . ";" : "") . $l10n["cart_qty"] . ";" . $l10n["cart_price"] . ";" . ($imVat ? $l10n["cart_vat"] .";" : "") . $l10n["cart_subtot"];
  102.            foreach($imOrderData as $od) {
  103.             $imOrderDataCSV .= "\n" . strip_tags(str_replace(array("\n", "\r"), "", $od["name"])) . ";" . strip_tags(str_replace(array("\n", "\r"), "", $od["description"])) . ";" . (($imOpt && $od["option"] != "null") ? $this->restoreSpecialChars(urldecode($od["option"])) . ";" : "") . $od["quantity"] . ";" . $od["single_price"] . ";" . ($imVat ? $od["price_vat"] .";" : "") . $od["price_vat"];
  104.             $imOrderDataTxt .= strip_tags(str_replace(array("\n", "\r"), "", $od["name"])) . " - " . strip_tags(str_replace(array("\n", "\r"), "", $od["description"])) . (($imOpt && $od["option"] != "null") ? " " . $this->restoreSpecialChars(urldecode($od["option"])) . ";" : "") . "\n " . $od["quantity"] . " x " . $od["single_price"] . " " . ($imVat ? "+ " . $l10n["cart_vat"] . " " . $od["vat_f"] : "") . " = " . $od["price_vat"] . "\n\n";
  105.             $imOrderDataHTML .= "\n\t\t\t\t<tr valign=\"top\" style=\"vertical-align: top\"" . ($i%2 ? " bgcolor=\"#EEEEEE\"" : "") . "><td style=\"border: 1px solid " . $imSettings['email']['body_background_border'] . ";\">" . $od["name"] . "<br />" . $od["description"] . "</td>" . ($imOpt ? "<td style=\"border: 1px solid " . $imSettings['email']['body_background_border'] . ";\">" . (($od["option"] != "null") ? $this->restoreSpecialChars(urldecode($od["option"])) : "") . "</td>" : "") . "<td  style=\"border: 1px solid " . $imSettings['email']['body_background_border'] . "; text-align: right;\">" . $od["quantity"] . "</td><td  style=\"border: 1px solid " . $imSettings['email']['body_background_border'] . "; text-align: right;\">" . $od["single_price"] . "</td>" . ($imVat ? "<td  style=\"border: 1px solid " . $imSettings['email']['body_background_border'] . "; text-align: right;\">" . (($od["vat"] != "null") ? $od["vat"]*100 . "% / " . $od["vat_f"] : "") ."</td>" : "") . "<td  style=\"border: 1px solid " . $imSettings['email']['body_background_border'] . "; text-align: right; width: " . $priceFieldWidth . "\">" . $od["price_vat"] . "</td></tr>\n";
  106.             $i++;
  107.            }
  108.  
  109.             // Payment Price
  110.  
  111.             if (isset($post_data['payment']['price']) && $post_data['payment']['price'] != null && $post_data['payment']['price'] != "null") {
  112.                 $imOrderDataHTML .= "<tr><td colspan=\"" . $colspan . "\"  style=\"border: 1px solid " . $imSettings['email']['body_background_border'] . "; text-align: right;\">" . $l10n['cart_payment'] . ": " . $post_data['payment']['name'] . "</td><td  style=\"border: 1px solid " . $imSettings['email']['body_background_border'] . "; text-align: right;\">" . $post_data['payment']['price'] . "</td></tr>";
  113.                 $imOrderDataTxt .= "\n" . $l10n['cart_payment'] . " - " . $post_data['payment']['name'] . ": " . $post_data['payment']['price'];
  114.             }
  115.             if (isset($post_data['shipping']['price']) && $post_data['shipping']['price'] != null && $post_data['shipping']['price'] != "null") {
  116.                 $imOrderDataHTML .= "<tr><td colspan=\"" . $colspan . "\"  style=\"border: 1px solid " . $imSettings['email']['body_background_border'] . "; text-align: right;\">" . $l10n['cart_shipping'] . ": " . $post_data['shipping']['name'] . "</td><td  style=\"border: 1px solid " . $imSettings['email']['body_background_border'] . "; text-align: right;\">" . $post_data['shipping']['price'] . "</td></tr>";
  117.                 $imOrderDataTxt .= "\n" . $l10n['cart_shipping'] . " - " . $post_data['shipping']['name'] . ": " . $post_data['shipping']['price'];
  118.             }
  119.  
  120.             $imOrderDataHTML .= "<tr><td colspan=\"" . $colspan . "\"  style=\"border: 1px solid " . $imSettings['email']['body_background_border'] . "; text-align: right;\">" . $l10n['cart_total_vat'] . "</td><td style=\"border: 1px solid " . $imSettings['email']['body_background_border'] . "; text-align: right;\">" . $post_data['total'] . "</td></tr>";
  121.             $imOrderDataTxt .= "\n" . $l10n['cart_total_vat']  . ": " . $post_data['total'];
  122.  
  123.             $imOrderDataHTML .= "</table>";
  124.         }
  125.  
  126.         $htmlMsg = $imSettings['email']['header'];
  127.  
  128.         $htmlMsg .= "<table border=0 width=\"100%\" style=\"font: inherit;\">\n";
  129.         // Opening message
  130.         $htmlMsg .= "<tr><td colspan=\"2\">" . $imSettings['cart']['email_opening'] . "</td></tr>\n";
  131.         $txtMsg = str_replace("<br />", "\n", $imSettings['cart']['email_opening']);
  132.  
  133.         // Order number
  134.         $htmlMsg .= "<tr><td colspan=\"2\" style=\"text-align: center; font-weight: bold;\">" . $l10n['cart_order_no'] . ": " . $imOrderNo . "</td></tr>\n";
  135.         $txtMsg .= "\n\n" . str_replace("<br />", "\n", $l10n['cart_order_no'] . ": " . $imOrderNo);
  136.  
  137.         // Vat data
  138.         if ($imShippingDataHtml != "") {
  139.             $htmlMsg .= "<tr style=\"vertical-align: top\" valign=\"top\"><td style=\"width: 50%; padding: 20px 0;\"><h3 style=\"font-size: 1.11em\">" . $l10n['cart_vat_address'] . "</h3>" . $imUserDataHtml . "</td>";
  140.             $htmlMsg .= "<td style=\"width: 50%; padding: 20px 0;\"><h3 style=\"font-size: 1.11em\">" . $l10n['cart_shipping_address'] . "</h3>" . $imShippingDataHtml . "</td></tr>";
  141.  
  142.             $txtMsg .= "\n" . str_replace("<br />", "\n", $l10n['cart_vat_address'] . "\n" . $imUserDataTxt);
  143.             $txtMsg .= "\n" . str_replace("<br />", "\n", $l10n['cart_shipping_address'] . "\n" . $imShippingDataTxt );
  144.         } else {
  145.             $htmlMsg .= "<tr><td colspan=\"2\" style=\"padding: 20px 0 0 0;\"><h3 style=\"font-size: 1.11em\">" . $l10n['cart_vat_address'] . "/" . $l10n['cart_shipping_address'] . "</h3>" . $imUserDataHtml . "</td></tr>";
  146.             $txtMsg .= "\n" . str_replace("<br />", "\n", $l10n['cart_vat_address'] . "/" . $l10n['cart_shipping_address'] . "\n" . $imUserDataTxt);
  147.         }
  148.  
  149.         $htmlMsg .= $separationLine;
  150.  
  151.         // Products
  152.         $htmlMsg .=  "<tr><td colspan=\"2\" style=\"padding: 5px 0 0 0;\"><h3 style=\"font-size: 1.11em\">" . $l10n['cart_product_list'] . "</h3>" . $imOrderDataHTML . "</td></tr>";
  153.         $txtMsg .= "\n\n" . str_replace("<br />", "\n", $l10n['cart_product_list'] . "\n" . $imOrderDataTxt);
  154.  
  155.         $htmlMsg .= $separationLine;
  156.  
  157.         // Payment
  158.         $htmlMsg .= "<tr><td colspan=\"2\" style=\"padding: 5px 0 0 0;\"><h3 style=\"font-size: 1.11em\">" . $l10n['cart_payment'] . "</h3>" . str_replace(array("\\'", '\\"'), array("'", '"'), str_replace("\\\"", "\"",  preg_replace('/[\n\r\t]*/', "", nl2br($post_data['payment']['email']))));
  159.         if ($post_data['payment']['html'] != null && $post_data['payment']['html'] != "" && $post_data['payment']['html'] != "null")
  160.             $htmlMsg .= "<br /><br /><div style=\"text-align: center;\">" . str_replace("\\\"", "\"", $post_data['payment']['html']) . "</div>";
  161.         $htmlMsg .= "</td></tr>";
  162.         $txtMsg .= "\n\n" . str_replace("<br />", "\n", $l10n['cart_payment'] . "\n" . str_replace(array("\\'", '\\"'), array("'", '"'), str_replace("\\\"", "\"",  $post_data['payment']['email'])));
  163.  
  164.         $htmlMsg .= $separationLine;
  165.  
  166.         // Shipping
  167.         $htmlMsg .= "<tr><td colspan=\"2\" style=\"padding: 5px 0 0 0;\"><h3 style=\"font-size: 1.11em\">" . $l10n['cart_shipping'] . "</h3>" . str_replace(array("\\'", '\\"'), array("'", '"'), str_replace("\\\"", "\"",  preg_replace('/[\n\r\t]*/', "", nl2br($post_data['shipping']['email'])))) . "</td></tr>";
  168.         $txtMsg .= "\n\n" . str_replace("<br />", "\n", $l10n['cart_shipping'] . "\n" . str_replace(array("\\'", '\\"'), array("'", '"'), str_replace("\\\"", "\"",  $post_data['shipping']['email'])));
  169.  
  170.         // Closing message
  171.         $htmlMsg .= $separationLine;
  172.         $htmlMsg .= "<tr><td colspan=\"2\" style=\"padding: 5px 0 0 0;\">" . str_replace(array("\\'", '\\"'), array("'", '"'), str_replace("\\\"", "\"",  $imSettings['cart']['email_closing'])) . "</td></tr>\n";
  173.         $txtMsg .= "\n\n" . str_replace(array("\\'", "\\\"", "<br />", "<br>"), array("'", "\"", "\n", "\n"), $imSettings['cart']['email_closing']);
  174.  
  175.         $htmlMsg .= "</table>\n";
  176.  
  177.         $htmlMsg .= $imSettings['email']['footer'];
  178.  
  179.         //Send email to user
  180.         $oEmail = new imEMail($ownerEmail,$post_data["form"]["imCartEmail"]["imValue"],$l10n['cart_order_no'] . " " . $imOrderNo,"utf-8");
  181.         $oEmail->setText($txtMsg);
  182.         $oEmail->setHTML($htmlMsg);
  183.         $oEmail->send();
  184.  
  185.         //Send email to owner
  186.         $txtMsg = "";
  187.         $htmlMsg = $imSettings['email']['header'];
  188.         $htmlMsg .= "<table border=0 width=\"100%\" style=\"font: inherit;\">\n";
  189.         // Order number
  190.         $htmlMsg .= "<tr><td colspan=\"2\" style=\"text-align: center; font-weight: bold;\">" . $l10n['cart_order_no'] . ": " . $imOrderNo . "</td></tr>\n";
  191.         $txtMsg .= "\n\n" . str_replace("<br />", "\n", $l10n['cart_order_no'] . ": " . $imOrderNo);
  192.  
  193.         // Vat data
  194.         if ($imShippingDataHtml != "") {
  195.             $htmlMsg .= "<tr style=\"vertical-align: top\" valign=\"top\"><td style=\"width: 50%; padding: 20px 0;\"><h3 style=\"font-size: 1.11em\">" . $l10n['cart_vat_address'] . "</h3>" . $imUserDataHtml . "</td>";
  196.             $htmlMsg .= "<td style=\"width: 50%; padding: 20px 0;\"><h3 style=\"font-size: 1.11em\">" . $l10n['cart_shipping_address'] . "</h3>" . $imShippingDataHtml . "</td></tr>";
  197.  
  198.             $txtMsg .= "\n" . str_replace("<br />", "\n", $l10n['cart_vat_address'] . "\n" . $imUserDataTxt);
  199.             $txtMsg .= "\n" . str_replace("<br />", "\n", $l10n['cart_shipping_address'] . "\n" . $imShippingDataTxt );
  200.         } else {
  201.             $htmlMsg .= "<tr><td colspan=\"2\" style=\"padding: 20px 0 0 0;\"><h3 style=\"font-size: 1.11em\">" . $l10n['cart_vat_address'] . "/" . $l10n['cart_shipping_address'] . "</h3>" . $imUserDataHtml . "</td></tr>";
  202.             $txtMsg .= "\n" . str_replace("<br />", "\n", $l10n['cart_vat_address'] . "/" . $l10n['cart_shipping_address'] . "\n" . $imUserDataTxt);
  203.         }
  204.  
  205.         $htmlMsg .= $separationLine;
  206.  
  207.         // Products
  208.         $htmlMsg .=  "<tr><td colspan=\"2\" style=\"padding: 5px 0 0 0;\"><h3 style=\"font-size: 1.11em\">" . $l10n['cart_product_list'] . "</h3>" . $imOrderDataHTML . "</td></tr>";
  209.         $txtMsg .= "\n\n" . str_replace("<br />", "\n", $l10n['cart_product_list'] . "\n" . $imOrderDataTxt);
  210.  
  211.         $oEmailO = new imEMail($ownerEmail,$ownerEmail,$l10n['cart_order_no'] . " " . $imOrderNo,"utf-8");
  212.         if ($imSettings['cart']['useCSV']) {
  213.             $txtMsg .= $imUserDataCSV . "\n" . $imOrderDataCSV;
  214.             $oEmailO->attachFile("user_data.csv",$imUserDataCSV,"text/csv");
  215.             $oEmailO->attachFile("order_data.csv",$imOrderDataCSV,"text/csv");
  216.         }
  217.         $oEmailO->setText($txtMsg);
  218.         $oEmailO->setHTML($htmlMsg);
  219.         return $oEmailO->send();
  220.     }
  221.  
  222.     /**
  223.      * Send the email message sent by the Email Object form
  224.      * @access public
  225.      * @param form The form settings in an associative array (array)
  226.      * @param form_data The posted text data in an associative array (array)
  227.      * @param files_data The posted files data in an associative array (array)
  228.      * @param user_only Set TRUE to send the email only to the customer who filled the form. This is used when the data is stored in a DB and a confirmation email is sent too (bool)
  229.      */
  230.     function sendFormEmail($form, $form_data, $files_data, $user_only = FALSE) {
  231.         global $imSettings;
  232.         if (!is_array($form))
  233.             $settings = $imSettings['email_form'][$form_id];
  234.         else
  235.             $settings = $form;
  236.         //Form Data
  237.         $txtData = "";
  238.         $htmData = "";
  239.         $csvHeader = "";
  240.         $csvData = "";
  241.         $keys = array_keys($form_data);
  242.         foreach ($keys as $key) {
  243.             if (is_array($form_data[$key])) {
  244.                 $txtData .= $key . ": " . implode(", ", $form_data[$key]) . "\r\n";
  245.                 $htmData .= "<tr valign=\"top\"><td width=\"25%\"><b>" . $key . ":</b></td><td>" . implode(", ", $form_data[$key]) . "</td></tr>";
  246.                 if ($settings['customer_csv'] || $settings['owner_csv']) {
  247.                     $csvHeader .= $key . ";";
  248.                     $csvData .= implode(", ", $form_data[$key]) . ";";
  249.                 }
  250.             } else {
  251.                 $txtData .= $key . ": " . $form_data[$key] . "\r\n";
  252.                 // Is it an email?
  253.                 if (preg_match('/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\@([a-z0-9])' . '(([a-z0-9-])*([a-z0-9]))+' . '(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i', $form_data[$key])) {
  254.                     $htmData .= "<tr valign=\"top\"><td width=\"25%\"><b>" . str_replace(array("\\'", '\\"'), array("'", '"'), $key) . ":</b></td><td><a href=\"mailto:" . $form_data[$key] . "\">". $form_data[$key] . "</a></td></tr>";
  255.                 } else if (preg_match('/^http[s]?:\/\/[a-zA-Z0-9\.\-]{2,}\.[a-zA-Z]{2,}/', $form_data[$key])) {
  256.                     // Is it an URL?
  257.                     $htmData .= "<tr valign=\"top\"><td width=\"25%\"><b>" . str_replace(array("\\'", '\\"'), array("'", '"'), $key) . ":</b></td><td><a href=\"" . $form_data[$key] . "\">". $form_data[$key] . "</a></td></tr>";
  258.                 } else {
  259.                     $htmData .= "<tr valign=\"top\"><td width=\"25%\"><b>" . str_replace(array("\\'", '\\"'), array("'", '"'), $key) . ":</b></td><td>" . str_replace(array("\\'", '\\"'), array("'", '"'), $form_data[$key]) . "</td></tr>";
  260.                 }
  261.                 if ($settings['customer_csv'] || $settings['owner_csv']) {
  262.                     $csvHeader .= str_replace(array("\\'", '\\"'), array("'", '"'), $key) . ";";
  263.                     $csvData .= str_replace(array("\\'", '\\"'), array("'", '"'), $form_data[$key]) . ";";
  264.                 }
  265.             }
  266.         }
  267.  
  268.         // Template
  269.         $htmHead = $imSettings['email']['header'];
  270.         $htmFoot = $imSettings['email']['footer'];
  271.  
  272.         //Send email to owner
  273.         if (!$user_only && isset($settings['owner_email_to']) && $settings['owner_email_to'] != "") {
  274.             $txtMsg = $settings['owner_message'];
  275.             $htmMsg = nl2br($settings['owner_message']);
  276.             if (strpos($settings['owner_email_from'], "@") === FALSE)
  277.                 $settings['owner_email_from'] = $form_data[$settings['owner_email_from']];
  278.             if ($settings['owner_email_from'] == "")
  279.                 $settings['owner_email_from'] = $settings['owner_email_to'];
  280.             $oEmail = new imEMail($settings['owner_email_from'],$settings['owner_email_to'],$settings['owner_subject'],"utf-8");
  281.             $oEmail->setText($txtMsg . "\n\n" . $txtData);
  282.             $oEmail->setHTML($htmHead . $htmMsg . "<br><br><table border=0 width=\"100%\" style=\"" . $imSettings['email']['email_content_style'] . "\">" . $htmData . "</table>" . $htmFoot);
  283.             if ($settings['owner_csv'])
  284.                 $oEmail->attachFile("form_data.csv", $csvHeader . "\n" . $csvData,"text/csv");
  285.             if (count($files_data) > 0) {
  286.                 foreach ($files_data as $file) {
  287.                     if (file_exists($file['tmp_name']))
  288.                         $oEmail->attachFile($file['name'], file_get_contents($file['tmp_name']), $file['type']);
  289.                 }
  290.             }
  291.             $oEmail->send();
  292.         }
  293.  
  294.         //Send email to user
  295.         if (isset($settings['customer_email_to']) && $settings['customer_email_to'] != "") {
  296.             $txtMsg = $settings['customer_message'];
  297.             $htmMsg = nl2br($settings['customer_message']);
  298.             if ($settings['customer_email_from'] == "")
  299.                 $settings['customer_email_from'] = $settings['owner_email_to'];
  300.             $oEmail = new imEMail($settings['customer_email_from'],$form_data[$settings['customer_email_to']],$settings['customer_subject'],"utf-8");
  301.             if ($settings['customer_csv']) {
  302.                 $oEmail->setHTML($htmHead . $htmMsg . "<br><br><table border=0 width=\"100%\" style=\"" . $imSettings['email']['email_content_style'] . "\">" . $htmData . "</table>" . $htmFoot);
  303.                 $oEmail->setText($txtMsg . "\n\n" . $txtData);
  304.             } else {
  305.                 $oEmail->setText($txtMsg);
  306.                 $oEmail->setHTML($htmHead . $htmMsg . $htmFoot);
  307.             }
  308.             $oEmail->send();
  309.         }
  310.     }
  311.  
  312.     /**
  313.      * Send the blog emails
  314.      * @access public
  315.      * @param post The comment data
  316.      */
  317.     function sendBlogEmail($post) {
  318.         global $imSettings;
  319.         global $l10n;
  320.         if (isset($post['post_id'])) {
  321.             $e = new imEmail($imSettings['blog']['email'],$imSettings['blog']['email'],$l10n['blog_new_comment_object'],"utf-8");
  322.             $text = $l10n['blog_new_comment_text'] . " \"" . $imSettings['blog']['posts'][$post['post_id']]['title'] . "\":\n\n";
  323.             $text .= $l10n['blog_name'] . " " . stripslashes($post['name']) . "\n";
  324.             $text .= $l10n['blog_email'] . " " . $post['email'] . "\n";
  325.             $text .= $l10n['blog_website'] . " " . $post['url'] . "\n";
  326.             $text .= $l10n['blog_message'] . " " . stripslashes($post['body']) . "\n\n";
  327.             $text .= ($imBCommentsApproved ? $l10n['blog_unapprove_link'] : $l10n['blog_approve_link']) . ":\n" . $imSettings['general']['url'] . "/admin/blog.php?post_id=" . $post['post_id'];
  328.             $e->setText($text);
  329.             return $e->send();
  330.         }
  331.  
  332.         return FALSE;
  333.     }
  334.     
  335.     /**
  336.      * Send the guestbook emails
  337.      * @access public
  338.      * @param post The comment data
  339.      */
  340.     function sendGuestbookEmail($id, $name, $email, $website, $body, $direct_approval, $owner_email) {
  341.         global $imSettings;
  342.         global $l10n;
  343.         if (isset($id)) {
  344.             $e = new imEmail($owner_email,$owner_email,str_replace(array("Blog", "blog"), array("Guestbook", "guestbook"), $l10n['blog_new_comment_object']),"utf-8");
  345.             $text = str_replace(array("Blog", "blog"), array("Guestbook", "guestbook"), $l10n['blog_new_comment_text']) . " \"" . $id . "\":\n\n";
  346.             $text .= $l10n['blog_name'] . " " . stripslashes($name) . "\n";
  347.             $text .= $l10n['blog_email'] . " " . $email . "\n";
  348.             $text .= $l10n['blog_website'] . " " . $website . "\n";
  349.             $text .= $l10n['blog_message'] . " " . stripslashes($body) . "\n\n";
  350.             $text .= ($direct_approval ? $l10n['blog_unapprove_link'] : $l10n['blog_approve_link']) . ":\n" . $imSettings['general']['url'] . "/admin/guestbook.php?post_id=" . $id;
  351.             $e->setText($text);
  352.             return $e->send();
  353.         }
  354.  
  355.         return FALSE;
  356.     }
  357.  
  358.     /**
  359.      * Restore some special chars escaped previously in WSX5
  360.      * @access public
  361.      * @param str The string to be restored
  362.      */
  363.     function restoreSpecialChars($str) {
  364.         $str = str_replace("{1}", "'", $str);
  365.         $str = str_replace("{2}", "\"", $str);
  366.         $str = str_replace("{3}", "\\", $str);
  367.         $str = str_replace("{4}", "<", $str);
  368.         $str = str_replace("{5}", ">", $str);
  369.         return $str;
  370.     }
  371. }
  372.  
  373. /**
  374.  * Contains the methods used by the search engine
  375.  * @access public
  376.  */
  377. class imSearch {
  378.  
  379.     var $scope;
  380.     var $page;
  381.     var $results_per_page;
  382.  
  383.     function __construct() {
  384.         $this->setScope();
  385.         $this->results_per_page = 10;
  386.     }
  387.  
  388.     function imSearch() {
  389.         $this->setScope();
  390.         $this->results_per_page = 10;
  391.     }
  392.  
  393.     /**
  394.      * Loads the pages defined in search.inc.php  to the search scope
  395.      * @access public
  396.      */
  397.     function setScope() {
  398.         global $imSettings;
  399.         $scope = $imSettings['search']['general']['defaultScope'];
  400.  
  401.         // Logged users can search in their private pages
  402.         $pa = new imPrivateArea();
  403.         if ($user = $pa->who_is_logged()) {
  404.             foreach ($imSettings['search']['general']['extendedScope'] as $key => $value) {
  405.                 if (in_array($user['uid'], $imSettings['access']['pages'][$key]))
  406.                     $scope[] = $value;
  407.             }
  408.         }
  409.  
  410.         $this->scope = $scope;
  411.     }
  412.  
  413.     /**
  414.      * Do the pages search
  415.      * @access public
  416.      * @param queries The search query (array)
  417.      */
  418.     function searchPages($queries) {
  419.         global $l10n;
  420.         global $imSettings;
  421.  
  422.         $html = "";
  423.  
  424.         if (is_array($this->scope)) {
  425.             foreach($this->scope as $filename) {
  426.                 $count = 0;
  427.                 $weight = 0;
  428.                 $file_content = @implode("\n",file($filename));
  429.  
  430.                 // Remove the breadcrumbs
  431.                 while (stristr($file_content, "<div id=\"imBreadcrumb\"") !== FALSE) {
  432.                     $style_start = strpos($file_content, "<div id=\"imBreadcrumb\"");
  433.                     $style_end = strpos($file_content, "</div", $style_start);
  434.                     $style = substr($file_content, $style_start, $style_end - $style_start);
  435.                     $file_content = str_replace($style, "", $file_content);
  436.                 }
  437.  
  438.                 // Remove CSS
  439.                 while (stristr($file_content, "<style") !== FALSE) {
  440.                     $style_start = strpos($file_content, "<style");
  441.                     $style_end = strpos($file_content, "</style", $style_start);
  442.                     $style = substr($file_content, $style_start, $style_end - $style_start);
  443.                     $file_content = str_replace($style, "", $file_content);
  444.                 }
  445.  
  446.                 // Remove JS
  447.                 while (stristr($file_content, "<script") !== FALSE) {
  448.                     $style_start = strpos($file_content, "<script");
  449.                     $style_end = strpos($file_content, "</script", $style_start);
  450.                     $style = substr($file_content, $style_start, $style_end - $style_start);
  451.                     $file_content = str_replace($style, "", $file_content);
  452.                 }
  453.                 $file_title = "";
  454.  
  455.                 // Get the title of the page
  456.                 preg_match('/\<title\>([^\<]*)\<\/title\>/', $file_content, $matches);
  457.                 if ($matches[1] != null)
  458.                     $file_title = $matches[1];
  459.                 else {
  460.                     preg_match('/\<h2\>([^\<]*)\<\/h2\>/', $file_content, $matches);
  461.                     if ($matches[1] != null)
  462.                         $file_title = $matches[1];
  463.                 }
  464.  
  465.                 if($file_title != "") {
  466.                     foreach($queries as $query) {
  467.                         $title = strtolower($file_title);
  468.                         while (($title = stristr($title, $query)) !== FALSE) {
  469.                             $weight += 5;
  470.                             $count++;
  471.                             $title = substr($title,strlen($query));
  472.                         }
  473.                     }
  474.                 }
  475.  
  476.                 // Get the keywords
  477.                 preg_match('/\<meta name\=\"keywords\" content\=\"([^\"]*)\" \/>/', $file_content, $matches);
  478.                 if ($matches[1] != null) {
  479.                     $keywords = $matches[1];
  480.                     foreach($queries as $query) {
  481.                         $tkeywords = strtolower($keywords);
  482.                         while (($tkeywords = stristr($tkeywords, $query)) !== FALSE) {
  483.                             $weight += 4;
  484.                             $count++;
  485.                             $tkeywords = substr($tkeywords,strlen($query));
  486.                         }
  487.                     }
  488.                 }
  489.  
  490.                 // Get the description
  491.                 preg_match('/\<meta name\=\"description\" content\=\"([^\"]*)\" \/>/', $file_content, $matches);
  492.                 if ($matches[1] != null) {
  493.                     $keywords = $matches[1];
  494.                     foreach($queries as $query) {
  495.                         $tkeywords = strtolower($keywords);
  496.                         while (($tkeywords = stristr($tkeywords, $query)) !== FALSE) {
  497.                             $weight += 3;
  498.                             $count++;
  499.                             $tkeywords = substr($tkeywords,strlen($query));
  500.                         }
  501.                     }
  502.                 }
  503.  
  504.                 // Remove the page title from the result
  505.                 while (stristr($file_content, "<h2") !== FALSE) {
  506.                     $style_start = strpos($file_content, "<h2");
  507.                     $style_end = strpos($file_content, "</h2", $style_start);
  508.                     $style = substr($file_content, $style_start, $style_end - $style_start);
  509.                     $file_content = str_replace($style, "", $file_content);
  510.                 }
  511.  
  512.                 $page_pos = strpos($file_content,"<div id=\"imContent\">") + strlen("<div id=\"imContent\">");
  513.                 $page_end = strpos($file_content, "<div id=\"imBtMn\">");
  514.                 if ($page_end == FALSE)
  515.                     $page_end = strpos($file_content,"</body>");
  516.  
  517.                 $file_content = strip_tags(substr($file_content,$page_pos, $page_end-$page_pos));
  518.                 $t_file_content = strtolower($file_content);
  519.  
  520.                 foreach($queries as $query) {
  521.                     $file = $t_file_content;
  522.                     while (($file = stristr($file, $query)) !== FALSE) {
  523.                         $count++;
  524.                         $weight++;
  525.                         $file = substr($file,strlen($query));
  526.                     }
  527.                 }
  528.  
  529.                 if($count > 0) {
  530.                     $found_count[$filename] = $count;
  531.                     $found_weight[$filename] = $weight;
  532.                     $found_content[$filename] = $file_content;
  533.                     if ($file_title == "")
  534.                         $found_title[$filename] = $filename;
  535.                     else
  536.                         $found_title[$filename] = $file_title;
  537.                 }
  538.             }
  539.         }
  540.  
  541.         if($found_count != null) {
  542.             arsort($found_weight);
  543.             $i = 0;
  544.             $pagine = ceil(count($found_count)/$this->results_per_page);
  545.             if(($this->page >= $pagine) || ($this->page < 0))
  546.                 $this->page = 0;
  547.             foreach($found_weight as $name => $weight) {
  548.                 $count = $found_count[$name];
  549.                 $i++;
  550.                 if(($i > $this->page*$this->results_per_page) && ($i <= ($this->page+1)*$this->results_per_page)) {
  551.                     $title = strip_tags($found_title[$name]);
  552.                     $file = $found_content[$name];
  553.                     $file = strip_tags($file);
  554.                     $ap = 0;
  555.                     $filelen = strlen($file);
  556.                     $text = "";
  557.                     for($j=0;$j<($count > 6 ? 6 : $count);$j++) {
  558.                         $minpos = $filelen;
  559.                         foreach($queries as $query) {
  560.                             if(($pos = strpos(strtoupper($file),strtoupper($query),$ap)) !== FALSE) {
  561.                                 if($pos < $minpos) {
  562.                                     $minpos = $pos;
  563.                                     $word = $query;
  564.                                 }
  565.                             }
  566.                         }
  567.                         $prev = explode(" ",substr($file,$ap,$minpos-$ap));
  568.                         if(count($prev) > ($ap > 0 ? 9 : 8))
  569.                             $prev = ($ap > 0 ? implode(" ",array_slice($prev,0,8)) : "") . " ... " . implode(" ",array_slice($prev,-8));
  570.                         else
  571.                             $prev = implode(" ",$prev);
  572.                         $text .= $prev . "<strong>" . substr($file,$minpos,strlen($word)) . "</strong> ";
  573.                         $ap = $minpos + strlen($word);
  574.                     }
  575.                     $next = explode(" ",substr($file,$ap));
  576.                     if(count($next) > 9)
  577.                         $text .= implode(" ",array_slice($next,0,8)) . "...";
  578.                     else
  579.                         $text .= implode(" ",$next);
  580.                     $text = str_replace("|", "", $text);
  581.                     $text = str_replace("<br />", " ", $text);
  582.                     $text = str_replace("<br>", " ", $text);
  583.                     $text = str_replace("\n", " ", $text);
  584.                     $html .= "<div class=\"imSearchPageResult\"><h3><a href=\"" . $name . "\">" . $title . "</a></h3>" . $text . "<div class=\"imSearchLink\"><a href=\"" . $name . "\">" . $domain . $name . "</a></div></div>\n";
  585.                 }
  586.             }
  587.             $html = preg_replace("/\\s+/", " ", $html);
  588.             $html .= "<div class=\"imSLabel\"> </div>\n";
  589.         }
  590.  
  591.         return array("content" => $html, "count" => count($found_content));
  592.     }
  593.  
  594.     /**
  595.      * Start the site search
  596.      * @access public
  597.      * @param keys The search keys as string (string)
  598.      * @param page Page to show (integer)
  599.      */
  600.     function search($keys, $page = "") {
  601.         global $l10n;
  602.         global $imSettings;
  603.  
  604.         $html = "";
  605.         $content = "";
  606.  
  607.         $html .= "<h2 id=\"imPgTitle\" class=\"searchPageTitle\">" . $l10n['search_results'] . "</h2>\n";
  608.         $html .= "<div class=\"searchPageContainer\">";
  609.         $html .= "<div class=\"imPageSearchField\"><form method=\"get\" action=\"imsearch.php\">";
  610.         $html .= "<input style=\"width: 200px; font: 8pt Tahoma; color: rgb(0, 0, 0); background-color: rgb(255, 255, 255); padding: 3px; border: 1px solid rgb(0, 0, 0); vertical-align: middle;\" class=\"search_field\" value=\"" . $keys . "\" type=\"text\" name=\"search\" />";
  611.         $html .= "<input style=\"height: 21px; font: 8pt Tahoma; color: rgb(0, 0, 0); background-color: rgb(211, 211, 211); margin-left: 6px; padding: 3px 3px; border: 1px solid rgb(0, 0, 0); vertical-align: middle; cursor: pointer;\" type=\"submit\" value=\"" . $l10n['search_search'] . "\">";
  612.         $html .= "</form></div>\n";
  613.  
  614.         if ($keys == "" || $keys == NULL) {
  615.             $html .= "<div style=\"margin-top: 15px; text-align: center; font-weight: bold;\">" . $l10n['search_empty'] . "</div>\n";
  616.             echo $html;
  617.             return FALSE;
  618.         }
  619.  
  620.         $domain = "";
  621.         $search = trim(strtolower($keys));
  622.         if($page == "" || $page == NULL)
  623.             $page = 0;
  624.  
  625.         $this->page = $page;
  626.  
  627.         if($search != "") {
  628.             $queries = explode(" ",$search);
  629.  
  630.             // Pages
  631.             $pages = $this->searchPages($queries);
  632.             if ($pages['count'] > 0) {
  633.                 $content .= "<div id=\"imSearchWebPages\">" . $pages['content'] . "</div>\n";
  634.             }
  635.  
  636.             $results_count = max($pages['count'], $blog['count'], $products['count'], $images['count'], $videos['count']);
  637.  
  638.             if ($pages['count'] == 0 && $blog['count'] == 0 && $products['count'] == 0 && $images['count'] == 0 && $videos['count'] == 0) {
  639.                 $html .= "<div style=\"margin-top: 15px; text-align: center; font-weight: bold;\">" . $l10n['search_empty'] . "</div>\n";
  640.             } else {
  641.                 $html .= "<div id=\"imSearchResults\">\n";
  642.                 $html .= "\t<div id=\"imSearchContent\">" . $content . "</div>\n";
  643.                 $html .= "</div>\n";
  644.             }
  645.  
  646.             // Pagination
  647.             if ($results_count > $this->results_per_page) {
  648.                 $html .= "<div style=\"text-align: center;\">";
  649.                 // Back
  650.                 if ($page > 0) {
  651.                     $html .= "<a href=\"imsearch.php?search=" . implode("+", $queries) . "&page=" . ($page - 1) . "\"><<</a> ";
  652.                 }
  653.  
  654.                 // Central pages
  655.                 $start = max($page - 5, 0);
  656.                 $end = min($page + 10 - $start, ceil($results_count/$this->results_per_page));
  657.  
  658.                 for ($i = $start; $i < $end; $i++) {
  659.                     if ($i != $this->page)
  660.                         $html .= "<a href=\"imsearch.php?search=" . implode("+", $queries) . "&page=" . $i . "\">" . ($i + 1) . "</a> ";
  661.                     else
  662.                         $html .= ($i + 1) . " ";
  663.                 }
  664.  
  665.                 // Next
  666.                 if ($results_count > ($page + 1) * $this->results_per_page) {
  667.                     $html .= "<a href=\"imsearch.php?search=" . implode("+", $queries) . "&page=" . ($page + 1) . "\">>></a>";
  668.                 }
  669.                 $html .= "</div>";
  670.             }
  671.  
  672.         } else
  673.             $html .= "<div style=\"margin-top: 15px; text-align: center; font-weight: bold;\">" . $l10n['search_empty'] . "</div>\n";
  674.  
  675.         $html .= "</div>";
  676.  
  677.         echo $html;
  678.     }
  679. }
  680.  
  681. /**
  682.  * Private area
  683.  * @access public
  684.  */
  685. class imPrivateArea {
  686.  
  687.     var $session_uname;
  688.     var $session_uid;
  689.     var $session_page;
  690.     var $cookie_name;
  691.  
  692.     // PHP 5
  693.     function __contruct() {
  694.         $this->session_uname = "im_access_uname";
  695.         $this->session_real_name = "im_access_real_name";
  696.         $this->session_page = "im_access_request_page";
  697.         $this->session_uid = "im_access_uid";
  698.         $this->cookie_name = "im_access_cookie_uid";
  699.     }
  700.  
  701.     // PHP 4
  702.     function imPrivateArea() {
  703.         $this->session_uname = "im_access_uname";
  704.         $this->session_real_name = "im_access_real_name";
  705.         $this->session_page = "im_access_request_page";
  706.         $this->session_uid = "im_access_uid";
  707.         $this->cookie_name = "im_access_cookie_uid";
  708.     }
  709.  
  710.     /**
  711.      * Login
  712.      * @access public
  713.      * @param uname Username (string)
  714.      * @param pwd Password (string)
  715.      */
  716.     function login($uname, $pwd) {
  717.         global $imSettings;
  718.  
  719.         // Check if the user exists
  720.         if ($imSettings['access']['users'][$uname] != NULL && $imSettings['access']['users'][$uname]['password'] == $pwd) {
  721.             // Save the session
  722.             $_SESSION[$this->session_uid] = $imSettings['access']['users'][$uname]['id'];
  723.             $_SESSION[$this->session_uname] = $uname;
  724.             $_SESSION[$this->session_real_name] = $imSettings['access']['users'][$uname]['name'];
  725.             setcookie($this->cookie_name, $imSettings['access']['users'][$uname]['id'], time() + 60 * 60 * 24 * 30, "/");
  726.             return TRUE;
  727.         }
  728.  
  729.         return FALSE;
  730.     }
  731.  
  732.     /**
  733.      * Logout
  734.      * @access public
  735.      */
  736.     function logout() {
  737.         $_SESSION[$this->session_uname] = "";
  738.         $_SESSION[$this->session_uid] = "";
  739.         setcookie($this->cookie_name, "", time() - 3600, "/");
  740.         $_COOKIE[$this->cookie_name] = "";
  741.     }
  742.  
  743.     /**
  744.      * Save the referrer page
  745.      * @access public
  746.      */
  747.     function save_page() {
  748.         $_SESSION[$this->session_page] = basename($_SERVER['PHP_SELF']);
  749.     }
  750.  
  751.     /**
  752.      * Return to the referrer page
  753.      * @access public
  754.      */
  755.     function saved_page() {
  756.         if ($_SESSION[$this->session_page] != "" && $_SESSION[$this->session_page] != null)
  757.             return $_SESSION[$this->session_page];
  758.         return FALSE;
  759.     }
  760.  
  761.     /**
  762.      * Get an array of data about the logged user
  763.      * @access public
  764.      */
  765.     function who_is_logged() {
  766.         if ($_SESSION[$this->session_uname] != "" && $_SESSION[$this->session_uname] != null)
  767.             return array(
  768.                 "username" => $_SESSION[$this->session_uname],
  769.                 "uid" => $_SESSION[$this->session_uid],
  770.                 "realname" => $_SESSION[$this->session_real_name],
  771.             );
  772.         return FALSE;
  773.     }
  774.  
  775.     /**
  776.      * Check if the logged user can access to a page
  777.      * @access public
  778.      * @param page The page id (string)
  779.      */
  780.     function checkAccess($page) {
  781.         global $imSettings;
  782.  
  783.         if ($_SESSION[$this->session_uname] == null || $_SESSION[$this->session_uname] == '' || $_SESSION[$this->session_uid] == null || $_SESSION[$this->session_uid] == '')
  784.             return -1; // Wrong login data
  785.  
  786.         $uid = $_SESSION[$this->session_uid];
  787.         if (!@in_array($uid, $imSettings['access']['pages'][$page]) && !@in_array($uid, $imSettings['access']['admins']))
  788.             return -2; // The user cannot access to this page
  789.  
  790.         return 0;
  791.     }
  792.  
  793.     /**
  794.      * Get the user's landing page
  795.      * @access public
  796.      */
  797.     function getLandingPage() {
  798.         global $imSettings;
  799.         if ($_SESSION[$this->session_uname] === null || $_SESSION[$this->session_uname] === '' || $_SESSION[$this->session_uid] === null || $_SESSION[$this->session_uid] === '')
  800.             return FALSE;
  801.  
  802.         return $imSettings['access']['users'][$_SESSION[$this->session_uname]]['page'];
  803.     }
  804. }
  805.  
  806. /**
  807.  * MySQL Storage class
  808.  * @access public
  809.  */
  810. class imDatabase {
  811.  
  812.     var $host_name;
  813.     var $db_name;
  814.     var $user_name;
  815.     var $password;
  816.     var $table_name;
  817.     var $file_storage;
  818.     var $field_names;
  819.     var $conn; //DB Connection handler
  820.  
  821.     /**
  822.      * PHP 5 Constuctor
  823.      * @param host_name (string)
  824.      * @param db_name (string)
  825.      * @param user_name (string)
  826.      * @param password (string)
  827.      * @param table_name (string)
  828.      * @param file_storage The folder in which the uploaded files are stored (string)
  829.      */
  830.     function __construct($host_name, $db_name, $user_name, $password, $table_name, $file_storage) {
  831.         $this->host_name = $host_name;
  832.         $this->db_name = $db_name;
  833.         $this->user_name = $user_name;
  834.         $this->password = $password;
  835.         $this->table_name = $table_name;
  836.         if ($file_storage[strlen($file_storage) - 1] == "/");
  837.             $file_storage = substr($file_storage, 0, strlen($file_storage) - 1);
  838.         $this->file_storage = $file_storage;
  839.         $this->field_names = array();
  840.         $this->conn = @mysql_connect($this->host_name, $this->user_name, $this->password);
  841.         if ($this->conn !== FALSE)
  842.             @mysql_set_charset("utf8",$this->conn);
  843.     }
  844.  
  845.     /**
  846.      * PHP 4 Constuctor
  847.      * @param host_name (string)
  848.      * @param db_name (string)
  849.      * @param user_name (string)
  850.      * @param password (string)
  851.      * @param table_name (string)
  852.      * @param file_storage The folder in which the uploaded files are stored (string)
  853.      */
  854.     function imDatabase($host_name, $db_name, $user_name, $password, $table_name, $file_storage) {
  855.         $this->host_name = $host_name;
  856.         $this->db_name = $db_name;
  857.         $this->user_name = $user_name;
  858.         $this->password = $password;
  859.         $this->table_name = $table_name;
  860.         if ($file_storage[strlen($file_storage) - 1] == "/");
  861.             $file_storage = substr($file_storage, 0, strlen($file_storage) - 1);
  862.         $this->file_storage = $file_storage;
  863.         $this->field_names = array();
  864.         $this->conn = @mysql_connect($this->host_name, $this->user_name, $this->password);
  865.         if ($this->conn !== FALSE)
  866.             @mysql_set_charset("utf8",$this->conn);
  867.     }
  868.  
  869.     function test_connection() {
  870.         return $this->conn;
  871.     }
  872.  
  873.     function __destruct() {
  874.         if ($this->conn)
  875.             mysql_close($this->conn);
  876.     }
  877.  
  878.     /**
  879.      * Save the data to the DB
  880.      * @param post an associative array as "tablefield_id" => "data_to_save"
  881.      * @param files an associative array. Normally it's $_FILES
  882.      */
  883.     function addData($post = null, $files = null) {
  884.         if ($post == null && $files == null)
  885.             return FALSE;
  886.         if ($post == null)
  887.             $post = array();
  888.         if ($files == null)
  889.             $files = array();
  890.         $empty = true;
  891.         foreach ($post as $field) {
  892.             if ($field != "" && $field != null)
  893.                 $empty = FALSE;
  894.         }
  895.         if ($empty)
  896.             return FALSE;
  897.         $fields_name = array_merge(array_keys($post), array_keys($files));
  898.         $fields_count = count($fields_name);
  899.         if (count($fields_name) < $fields_count) {
  900.             $d = $fields_count - count($fields_name);
  901.             for ($i = 0; $i < $d; $i++)
  902.                 $field_name[] = "field_" + ($i + $d);
  903.         }
  904.  
  905.         // If the table does not exists, create it
  906.         $result = mysql_query("SHOW FULL TABLES FROM `" . $this->db_name . "` LIKE '" . $this->table_name . "'", $this->conn);
  907.         if ($result && mysql_num_rows($result) == 0) {
  908.             $query = "CREATE TABLE `" . $this->db_name . "`.`" . $this->table_name . "` (`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,";
  909.             for ($i=0; $i<$fields_count; $i++) {
  910.                 $query .= "`" . $fields_name[$i] . "` TEXT CHARACTER SET utf8 COLLATE utf8_bin NOT NULL";
  911.                 if ($i != $fields_count - 1)
  912.                     $query .= ",";
  913.             }
  914.             $query .= ") ENGINE = MYISAM ;";
  915.             mysql_query($query, $this->conn);
  916.         }
  917.         else // If the table has not enough fields, update it
  918.         {
  919.             $result = mysql_query("SHOW COLUMNS FROM `" . $this->db_name . "`.`" . $this->table_name . "`", $this->conn);
  920.             if ($result) {
  921.                 // Actual fields
  922.                 $row = mysql_fetch_array($result);
  923.                 $query = "ALTER TABLE `" . $this->db_name. "`.`" . $this->table_name . "`";
  924.                 $act_fields = array();
  925.                 while ($row = mysql_fetch_array($result))
  926.                     $act_fields[] = $row[0];
  927.                 // New fields
  928.                 $new_fields = array_diff($fields_name, $act_fields);
  929.                 $new_fields = array_merge($new_fields); //ordina gli indici
  930.                 if (count($new_fields) > 0) {
  931.                     for ($j = 0; $j < count($new_fields); $j++) {
  932.                         $query .= " ADD `" . $new_fields[$j] . "` TEXT CHARACTER SET utf8 COLLATE utf8_bin NOT NULL ";
  933.                         if ($j != count($new_fields) - 1)
  934.                             $query .= ",";
  935.                     }
  936.                     mysql_query($query, $this->conn);
  937.                 }
  938.             }
  939.         }
  940.  
  941.         // Save
  942.         $query = "INSERT INTO `" . $this->db_name . "`.`" . $this->table_name . "` (";
  943.         $fields = array();
  944.         for ($i = 0; $i<$fields_count; $i++)
  945.             array_push ($fields,  $fields_name[$i]);
  946.         $query .= join(",", $fields);
  947.         $query .= ") VALUES (";
  948.  
  949.         $data = array();
  950.         $p_keys = array_keys($post);
  951.         for ($i = 0; $i<count($post); $i++) {
  952.             if (is_array($post[$p_keys[$i]])) {
  953.                 $s = "";
  954.                 for ($x = 0; $x < count($post[$p_keys[$i]]); $x++)
  955.                     $s .= (($x > 0) ? ", " : "") . $post[$p_keys[$i]][$x];
  956.                 array_push($data, "'" . mysql_real_escape_string(str_replace(array("\n", "\r"), array("<br />", ""), $s)). "'");
  957.             } else {
  958.                 array_push($data, "'" . mysql_real_escape_string(str_replace(array("\n", "\r"), array("<br />", ""), $post[$p_keys[$i]])). "'");
  959.             }
  960.         }
  961.  
  962.         $p_keys = array_keys($files);
  963.         $f = true;
  964.         for ($i = 0; $i<count($files); $i++) {
  965.             if ($files[$p_keys[$i]]['tmp_name'] != "") {
  966.                 // Upload files using an unique name
  967.                 $fname = $this->findFileName($files[$p_keys[$i]]['name']);
  968.                 if (@move_uploaded_file($files[$p_keys[$i]]['tmp_name'], ($this->file_storage != "" ? $this->file_storage . "/" : "../") . $fname)) {
  969.                   $f = true;
  970.                 } else {
  971.                   $f = FALSE;
  972.                 }
  973.                 array_push($data, "'" . mysql_real_escape_string($fname). "'");
  974.             }
  975.             else {
  976.                 array_push($data, "''");
  977.             }
  978.         }
  979.         $query .= join(",", $data);
  980.         $query .=")";
  981.  
  982.         $r = mysql_query($query, $this->conn);
  983.  
  984.         if ($r && $f)
  985.             return true;
  986.         return FALSE;
  987.     }
  988.  
  989.     /**
  990.      * Set the field names
  991.      * @param array An array containing the field names (array)
  992.      */
  993.     function setFieldNames($array) {
  994.         $this->field_names = $array;
  995.     }
  996.  
  997.     /**
  998.      * Show the current storage table (read only version)
  999.      * @param order ASC or DESC
  1000.      */
  1001.     function showTable($order = "ASC") {
  1002.         $result = mysql_query("SHOW COLUMNS FROM `" . $this->db_name . "`.`" . $this->table_name . "`", $this->conn);
  1003.         if ($result && mysql_num_rows($result)>1) {
  1004.             echo "<table class=\"imDbTable\">\n";
  1005.             echo "    <tr>\n";
  1006.             $row = mysql_fetch_array($result);
  1007.           for ($i=1; $i<mysql_num_rows($result); $i++) {
  1008.             $row = mysql_fetch_array($result);
  1009.             if (array_key_exists($i-1, $this->field_names)) $field = $this->field_names[$i - 1];
  1010.             else     $field = $row[0];
  1011.             echo "        <td class='imDbTableHead'>" . $field . "</td>\n";
  1012.             }
  1013.             echo "    </tr>\n";
  1014.             $result = mysql_query("SELECT * FROM `" . $this->db_name. "`.`" . $this->table_name . "` ORDER BY id " . $order, $this->conn);
  1015.             while ($row = mysql_fetch_array($result)){
  1016.                 echo "    <tr>\n";
  1017.                     for ($i = 1; $i < mysql_num_fields($result); $i++) {
  1018.                         if (file_exists($this->file_storage . "/" . $row[$i]))
  1019.                             echo "        <td><a href=\""  . $this->file_storage . "/" . $row[$i] . "\" target=\"_blank\">" . $row[$i] . "</a></td>\n";
  1020.                         else
  1021.                             echo "        <td>" . $row[$i] . "</td>\n";
  1022.                     }
  1023.                 echo "    </tr>\n";
  1024.             }
  1025.             echo "</table>\n";
  1026.         }
  1027.     }
  1028.  
  1029.     /**
  1030.      * Show the current storage table (r/w version)
  1031.      * @param order ASC or DESC
  1032.      */
  1033.     function showAdminTable($order = "ASC") {
  1034.         $form_id = "tt_form_" . rand(0, 10000000);
  1035.         $result = mysql_query("SHOW COLUMNS FROM `" . $this->db_name . "`.`" . $this->table_name . "`", $this->conn);
  1036.         if ($result && mysql_num_rows($result)>1) {
  1037.             echo "<form id=\"" . $form_id . "\" method=\"post\" action=\"" . $_SERVER['PHP_SELF'] . "?delete\" onsubmit=\"return confirm('Sei sicuro di voler confermare l\'operazione?');\">\n";
  1038.             echo "<table class=\"imDbTable\">\n";
  1039.             echo "    <tr>\n";
  1040.             $row = mysql_fetch_array($result);
  1041.             for ($i=1; $i<mysql_num_rows($result); $i++) {
  1042.                 $row = mysql_fetch_array($result);
  1043.                 if (array_key_exists($i-1, $this->field_names)) $field = $this->field_names[$i - 1];
  1044.                 else     $field = $row[0];
  1045.                 echo "        <td class='imDbTableHead'>" . $field . "</td>\n";
  1046.             }
  1047.             echo "    </tr>\n";
  1048.             $result = mysql_query("SELECT * FROM `" . $this->db_name. "`.`" . $this->table_name . "` ORDER BY id " . $order, $this->conn);
  1049.             while ($row = mysql_fetch_array($result)){
  1050.                 echo "    <tr>\n";
  1051.                     for ($i = 1; $i < mysql_num_fields($result); $i++) {
  1052.                         if (file_exists($this->file_storage . "/" . $row[$i]) && !is_dir($this->file_storage . "/" . $row[$i]))
  1053.                             echo "        <td><a href=\""  . $this->file_storage . "/" . $row[$i] . "\" target=\"_blank\">" . $row[$i] . "</a></td>\n";
  1054.                         else
  1055.                             echo "        <td>" . $row[$i] . "</td>\n";
  1056.                     }
  1057.                 echo "        <td><input type=\"checkbox\" value=\"" . $row[0] . "\" name=\"" . $row[0] . "\"></td>\n";
  1058.                 echo "    </tr>\n";
  1059.             }
  1060.             echo "    <tr>\n";
  1061.             echo "        <td colspan=\"" . $i . "\" style=\"text-align:right\">Se selezionati: <input type=\"submit\" value=\"Elimina\"></td>\n";
  1062.             echo "    </tr>\n";
  1063.             echo "</table></form>\n";
  1064.         }
  1065.     }
  1066.  
  1067.     /**
  1068.      * Find a free file name
  1069.      */
  1070.     function findFileName($tmp_name) {
  1071.         $ext = substr($tmp_name, strrpos($tmp_name, "."));
  1072.         $fname = basename($tmp_name, $ext);
  1073.         do {
  1074.             $rname = $fname . "_" . date("Ymdhisu") . $ext;
  1075.         } while (file_exists($this->file_storage . "/" . $rname));
  1076.         return $rname;
  1077.     }
  1078.  
  1079.     /**
  1080.      * Delete a row from the storage table
  1081.      * @param post The ids of the rows to deleted
  1082.      */
  1083.     function deleteRow($post) {
  1084.         if ($post != null) {
  1085.             $results = mysql_query("SELECT * FROM `" . $this->db_name . "`.`" . $this->table_name . "` WHERE id IN (" . join(",", $post) . ")", $this->conn);
  1086.             //Segna come eliminati i file linkati
  1087.             while ($results && $row = mysql_fetch_array($results))
  1088.                 for ($i = 1; $i < mysql_num_fields($results); $i++)
  1089.                     if (file_exists($this->file_storage . "/" . $row[$i]) && !is_dir($this->file_storage . "/" . $row[$i]))
  1090.                         rename($this->file_storage . "/" . $row[$i], $this->file_storage . "/" . $row[$i] . ".deleted");
  1091.             //Cancella i record
  1092.             mysql_query("DELETE FROM `" . $this->db_name . "`.`" . $this->table_name . "` WHERE id IN (" . join(",", $post) . ")", $this->conn);
  1093.         }
  1094.     }
  1095. }
  1096.  
  1097. /**
  1098.  * XML Handling class
  1099.  * @access public
  1100.  */
  1101. class imXML {
  1102.     var $tree = array();
  1103.     var $force_to_array = array();
  1104.     var $error = null;
  1105.     var $parser;
  1106.  
  1107.     // PHP 5
  1108.     function __construct($encoding = 'UTF-8') {
  1109.         $this->parser = xml_parser_create($encoding);
  1110.         xml_set_object($this->parser, $this); // $this was passed as reference &$this
  1111.         xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
  1112.         xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1);
  1113.         xml_set_element_handler($this->parser, "startEl", "stopEl");
  1114.         xml_set_character_data_handler($this->parser, "charData");
  1115.         xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
  1116.     }
  1117.  
  1118.     // PHP 4
  1119.     function imXML($encoding = 'UTF-8') {
  1120.         $this->parser = xml_parser_create($encoding);
  1121.         xml_set_object($this->parser, $this); // $this was passed as reference &$this
  1122.         xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);
  1123.         xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1);
  1124.         xml_set_element_handler($this->parser, "startEl", "stopEl");
  1125.         xml_set_character_data_handler($this->parser, "charData");
  1126.         xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
  1127.     }
  1128.  
  1129.     function parse_file($file) {
  1130.         $fp = @fopen($file, "r");
  1131.         if (!$fp)
  1132.             return FALSE;
  1133.         while ($data = fread($fp, 4096)) {
  1134.             if (!xml_parse($this->parser, $data, feof($fp))) {
  1135.                 return FALSE;
  1136.             }
  1137.         }
  1138.         fclose($fp);
  1139.         return $this->tree[0]["content"];
  1140.     }
  1141.  
  1142.     function parse_string($str) {
  1143.         if (!xml_parse($this->parser, $str))
  1144.             return FALSE;
  1145.         return $this->tree[0]["content"];
  1146.     }
  1147.  
  1148.     function startEl($parser, $name, $attrs) {
  1149.         array_unshift($this->tree, array("name" => $name));
  1150.     }
  1151.  
  1152.     function stopEl($parser, $name) {
  1153.         if ($name != $this->tree[0]["name"])
  1154.             return FALSE;
  1155.         if (count($this->tree) > 1) {
  1156.             $elem = array_shift($this->tree);
  1157.             if (isset($this->tree[0]["content"][$elem["name"]])) {
  1158.                 if (is_array($this->tree[0]["content"][$elem["name"]]) && isset($this->tree[0]["content"][$elem["name"]][0])) {
  1159.                     array_push($this->tree[0]["content"][$elem["name"]], $elem["content"]);
  1160.                 } else {
  1161.                     $this->tree[0]["content"][$elem["name"]] =
  1162.                     array($this->tree[0]["content"][$elem["name"]],$elem["content"]);
  1163.                 }
  1164.             } else {
  1165.                 if (in_array($elem["name"],$this->force_to_array)) {
  1166.                     $this->tree[0]["content"][$elem["name"]] = array($elem["content"]);
  1167.                 } else {
  1168.                     if (!isset($elem["content"])) $elem["content"] = "";
  1169.                     $this->tree[0]["content"][$elem["name"]] = $elem["content"];
  1170.                 }
  1171.             }
  1172.         }
  1173.     }
  1174.  
  1175.     function charData($parser, $data) {
  1176.         if (!is_string($this->tree[0]["content"]) && !preg_match("/\\S/", $data))
  1177.             return FALSE;
  1178.         $this->tree[0]["content"] .= $data;
  1179.     }
  1180. }
  1181.  
  1182.  
  1183. /**
  1184.  * Captcha handling class
  1185.  * @access public
  1186.  */
  1187. class imCaptcha {
  1188.  
  1189.     /**
  1190.      * Show the captcha chars
  1191.      */
  1192.     function show($sCode) {
  1193.         global $oNameList;
  1194.         global $oCharList;
  1195.  
  1196.         $text = "<!DOCTYPE HTML>
  1197.             <html>
  1198.           <head>
  1199.           <meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">
  1200.           <meta http-equiv=\"pragma\" content=\"no-cache\">
  1201.           <meta http-equiv=\"cache-control\" content=\"no-cache, must-revalidate\">
  1202.           <meta http-equiv=\"expires\" content=\"0\">
  1203.           <meta http-equiv=\"last-modified\" content=\"\">
  1204.           </head>
  1205.           <body style=\"margin: 0; padding: 0; border-collapse: collapse;\">";
  1206.  
  1207.         for ($i=0; $i<strlen($sCode); $i++)
  1208.             $text .= "<img style=\"margin:0; padding:0; border: 0; border-collapse: collapse; width: 24px; height: 24px; position: absolute; top: 0; left: " . (24 * $i) . "px;\" src=\"imcpa_".$oNameList[substr($sCode,$i,1)].".gif\" width=\"24\" height=\"24\">";
  1209.  
  1210.         $text .= "</body></html>";
  1211.  
  1212.         return $text;
  1213.     }
  1214.  
  1215.     /**
  1216.      * Check the sent data
  1217.      * @param sCode The correct code (string)
  1218.      * @param dans The user's answer (string)
  1219.      */
  1220.     function check($sCode, $ans) {
  1221.         global $oCharList;
  1222.         if ($ans == "")
  1223.             return '-1';
  1224.         for ($i=0; $i<strlen($sCode); $i++)
  1225.           if ($oCharList[substr(strtoupper($sCode),$i,1)] != substr(strtoupper($ans), $i,1))
  1226.             return '-1';
  1227.         return '0';
  1228.     }
  1229. }
  1230.  
  1231. /**
  1232.  * Comments
  1233.  * @access public
  1234.  */
  1235. class imComment {
  1236.  
  1237.     /**
  1238.      * Get the comments from a file
  1239.      * @param file The source file path
  1240.      */
  1241.     function getComments($file) {
  1242.         $xml = new imXML();
  1243.         $comments = $xml->parse_file($file);
  1244.         if (is_array($comments)) {
  1245.             if (!is_array($comments['comment'][0])) {
  1246.                 return str_replace(array("\\'", '\\"'), array("'", '"'), array($comments['comment']));
  1247.             } else {
  1248.                 for ($i = 0; $i < count($comments['comment']); $i++) {
  1249.                     $comments['comment'][$i]['body'] = str_replace(array("\\'", '\\"'), array("'", '"'), $comments['comment'][$i]['body']);
  1250.                     $comments['comment'][$i]['name'] = str_replace(array("\\'", '\\"'), array("'", '"'), $comments['comment'][$i]['name']);
  1251.                     $comments['comment'][$i]['body'] = str_replace("\\\"", "\"", $comments['comment'][$i]['body']);
  1252.                     $comments['comment'][$i]['name'] = str_replace("\\\"", "\"", $comments['comment'][$i]['name']);
  1253.                 }
  1254.                 return $comments['comment'];
  1255.             }
  1256.         }
  1257.         else
  1258.             return $this->getComments_old($file);
  1259.     }
  1260.  
  1261.     /**
  1262.      * Get the comments from a v8 comments file
  1263.      * @param file The source file path
  1264.      */
  1265.     function getComments_old($file) {
  1266.         if(file_exists($file)) {
  1267.             $f = file_get_contents($file);
  1268.             $f = explode("\n",$f);
  1269.             for($i = 0;$i < count($f)-1; $i += 6) {
  1270.                 $c[$i/6]['name'] = stripslashes($f[$i]);
  1271.                 $c[$i/6]['email'] = $f[$i+1];
  1272.                 $c[$i/6]['url'] = $f[$i+2];
  1273.                 $c[$i/6]['body'] = stripslashes($f[$i+3]);
  1274.                 $c[$i/6]['timestamp'] = $f[$i+4];
  1275.                 $c[$i/6]['approved'] = $f[$i+5];
  1276.                 $c[$i/6]['rating'] = 0;
  1277.             }
  1278.             return $c;
  1279.         }
  1280.         else
  1281.           return -1;
  1282.     }
  1283.  
  1284.     /**
  1285.      * Save the comments in a xml file
  1286.      * @param file The destination file path
  1287.      * @param comments An associative array containing the comments data
  1288.      */
  1289.     function writeXML($file, $comments) {
  1290.         if (count($comments) > 0) {
  1291.             $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  1292.             $xml .= "<comments>\n";
  1293.             foreach ($comments as $comment) {
  1294.                 $xml .= "\t<comment>\n";
  1295.                 $keys = array_keys($comment);
  1296.                 foreach ($keys as $key)
  1297.                     $xml .= "\t\t<" . $key . "><![CDATA[" . str_replace(array("\\'", '\\"'), array("'", '"'), str_replace("\\\"", "\"",  preg_replace('/[\n\r\t]*/', "", nl2br($comment[$key])))) . "]]></" . $key . ">\n";
  1298.                 $xml .= "\t</comment>\n";
  1299.             }
  1300.             $xml .= "</comments>";
  1301.         } else $xml = "";
  1302.  
  1303.         if (is_writable($file) || !file_exists($file)) {
  1304.             if (!$f = fopen($file, 'w+'))
  1305.                 return -3;
  1306.             else {
  1307.                 if (flock($f, LOCK_EX))
  1308.                     $locked = 1;
  1309.                 if (fwrite($f, $xml) === FALSE)
  1310.                     return -4;
  1311.                 else {
  1312.                     if($locked)
  1313.                         flock($f, LOCK_UN);
  1314.                     fclose($f);
  1315.                     return 0;
  1316.                 }
  1317.             }
  1318.         }
  1319.         else
  1320.           return -2;
  1321.     }
  1322.  
  1323.     /**
  1324.      * Add a comment to a file
  1325.      * @param file The destination file path
  1326.      * @param name The user's name
  1327.      * @param email The user's email
  1328.      * @param url The user's site url
  1329.      * @param body The user's message
  1330.      * @param abuse Set 1 to mark the message as an abuse
  1331.      * @param approved Set 1 to mark the message as approved
  1332.      */
  1333.     function addComment($file,$name,$email,$url,$body,$abuse = "0",$approved = 0) {
  1334.         global $imSettings;
  1335.         
  1336.         $name = filterCode($name);
  1337.         $email = filterCode($email);
  1338.         $url = filterCode($url);
  1339.         $body = filterCode($body);
  1340.         
  1341.         $locked = 0;
  1342.         $comments = $this->getComments($file);
  1343.         if (!is_array($comments))
  1344.             $comments = array();
  1345.         if ($url != "" && stripos($url, "http://") === FALSE)
  1346.             $url = "http://" . $url;
  1347.         $comments[] = array("name" => $name, "email" => $email, "url" => $url, "body" => $body, "abuse" => $abuse, "timestamp" => date("d-m-Y H:i:s"), "approved" => $approved);
  1348.         if($file != "" && trim($name) != "" && trim($email) != "" && trim($body) != "")
  1349.             return $this->writeXML($file, $comments);
  1350.         else
  1351.             return -1;
  1352.     }
  1353.  
  1354.     /**
  1355.      * Add a comment to a file
  1356.      * @param file The destination file
  1357.      * @param n The comment number (0 is the first comment)
  1358.      * @param approved Set 1 to approve the comment, 0 to unapprove
  1359.      */
  1360.     function approveComment($file,$n,$approved) {
  1361.         $locked = 0;
  1362.         $fn = $file;
  1363.         if(!copy($fn,$fn . "_bak"))
  1364.           return -1;
  1365.         $c = $this->getComments($file);
  1366.         if($c == -1)
  1367.           return -2;
  1368.         if(!file_exists($fn))
  1369.           return -3;
  1370.         if(!is_writable($fn))
  1371.           return -4;
  1372.         $c[$n - 1]['approved'] = $approved;
  1373.         $this->writeXML($file, $c);
  1374.         return 0;
  1375.     }
  1376.  
  1377.     /**
  1378.      * Delete a comment
  1379.      * @param file The destination file
  1380.      * @param n The comment number (0 is the first comment)
  1381.      */
  1382.     function removeComment($file,$n) {
  1383.         $locked = 0;
  1384.         $fn = $file;
  1385.         if(!copy($fn,$fn . "_bak"))
  1386.           return -1;
  1387.         $c = $this->getComments($file);
  1388.         if($c == -1)
  1389.           return -2;
  1390.         if(!file_exists($fn))
  1391.           return -3;
  1392.         if(!is_writable($fn))
  1393.           return -4;
  1394.         for ($i = 0; $i < count($c); $i++) {
  1395.             if ($i != $n - 1)
  1396.                 $comments[] = $c[$i];
  1397.         }
  1398.         $this->writeXML($file, $comments);
  1399.         return 0;
  1400.     }
  1401.  
  1402.     /**
  1403.      * Set the abuse
  1404.      * @param file The destination file
  1405.      * @param n The comment number (0 is the first comment)
  1406.      * @param abuse Set 1 to set as an abuse
  1407.      */
  1408.     function setAbuse($file, $n, $abuse) {
  1409.         $locked = 0;
  1410.         $fn = $file;
  1411.         if(!copy($fn,$fn . "_bak"))
  1412.           return -1;
  1413.         $c = $this->getComments($file);
  1414.         if($c == -1)
  1415.           return -2;
  1416.         if(!file_exists($fn))
  1417.           return -3;
  1418.         if(!is_writable($fn))
  1419.           return -4;
  1420.         $c[$n - 1]['abuse'] = $abuse;
  1421.         $this->writeXML($file, $c);
  1422.         return 0;
  1423.     }
  1424. }
  1425.  
  1426. /**
  1427.  * Blog class
  1428.  * @access public
  1429.  */
  1430. class imBlog {
  1431.  
  1432.     var $comments; //Comments class
  1433.  
  1434.     // PHP 5
  1435.     function __construct() {
  1436.         $this->comments = new imComment();
  1437.     }
  1438.  
  1439.     // PHP 4
  1440.     function imBlog() {
  1441.         $this->comments = new imComment();
  1442.     }
  1443.  
  1444.     function formatTimestamp($ts) {
  1445.         return date("d/m/Y H:i:s", strtotime($ts));
  1446.     }
  1447.  
  1448.     /**
  1449.      * Get the comments from a post
  1450.      * @param post the post ID
  1451.      */
  1452.     function getComments($post) {
  1453.         global $imSettings;
  1454.         return $this->comments->getComments($imSettings['general']['dir'] . $imSettings['blog']['file_prefix'] . 'pc' . $post);
  1455.     }
  1456.  
  1457.     /**
  1458.      * Add a comment to a post
  1459.      * @param post the post ID
  1460.      * @param file The destination file path
  1461.      * @param name The user's name
  1462.      * @param email The user's email
  1463.      * @param url The user's site url
  1464.      * @param body The user's message
  1465.      */
  1466.     function addComment($post,$name,$email,$url,$body) {
  1467.         global $imSettings;
  1468.         if (!file_exists($imSettings['general']['dir']) && $imSettings['general']['dir'] != "" && $imSettings['general']['dir'] != "./.")
  1469.             mkdir($imSettings['general']['dir'], 0777, TRUE);
  1470.         return $this->comments->addComment($imSettings['general']['dir'] . $imSettings['blog']['file_prefix'] . 'pc' . $post,$name,$email,$url,$body, "0", ($imSettings['blog']['approve_comments'] == 1) ? 0 : 1);
  1471.     }
  1472.  
  1473.     /**
  1474.      * Approve a comment
  1475.      * @param post the post ID
  1476.      * @param n The comment number
  1477.      * @param approved Set 1 to approve
  1478.      */
  1479.     function approveComment($post,$n,$approved) {
  1480.         global $imSettings;
  1481.         return $this->comments->approveComment($imSettings['general']['dir'] . $imSettings['blog']['file_prefix'] . 'pc' . $post,$n,$approved);
  1482.     }
  1483.  
  1484.     /**
  1485.      * Remove a comment
  1486.      * @param post the post ID
  1487.      * @param n The comment number
  1488.      */
  1489.     function removeComment($post,$n) {
  1490.         global $imSettings;
  1491.         return $this->comments->removeComment($imSettings['general']['dir'] . $imSettings['blog']['file_prefix'] . 'pc' . $post, $n);
  1492.     }
  1493.  
  1494.     /**
  1495.      * Abuse a comment
  1496.      * @param post the post ID
  1497.      * @param n The comment number
  1498.      * @param abuse Set 1 to abuse
  1499.      */
  1500.     function setAbuse($post, $n, $abuse) {
  1501.         global $imSettings;
  1502.         return $this->comments->setAbuse($imSettings['general']['dir'] . $imSettings['blog']['file_prefix'] . 'pc' . $post, $n, $abuse);
  1503.     }
  1504.  
  1505.     /**
  1506.      * Get the last update date
  1507.      */
  1508.     function getLastModified() {
  1509.         global $imSettings;
  1510.         $c = $this->comments->getComments($_GET['id']);
  1511.         if($_GET['id'] != "" && $c != -1) {
  1512.           return $this->formatTimestamp($c[count($c)-1]['timestamp']);
  1513.         }
  1514.         else {
  1515.           $last_post = $imSettings['blog']['posts'];
  1516.           $last_post = array_shift($last_post);
  1517.           return $last_post['timestamp'];
  1518.         }
  1519.     }
  1520.  
  1521.     /**
  1522.      * Show a post
  1523.      * @param id the post id
  1524.      * @param ext Set 1 to show as extended
  1525.      * @param first Set 1 if this is the first post in the list
  1526.      */
  1527.     function showPost($id,$ext=0,$first=0) {
  1528.         global $imSettings;
  1529.         global $l10n;
  1530.         $bp = $imSettings['blog']['posts'][$id];
  1531.  
  1532.         echo "<h2 id=\"imPgTitle\" style=\"display: block;\">" . $bp['title'] . "</h2>\n";
  1533.         echo "<div class=\"imBreadcrumb\" style=\"display: block;\">" . $l10n['blog_published_by'] . "<strong> " . $bp['author'] . " </strong>";
  1534.         echo $l10n['blog_in'] . " <a href=\"?category=" . $bp['category'] . "\" target=\"_blank\" rel=\"nofollow\">" . $bp['category'] . "</a> • " . $bp['timestamp'];
  1535.  
  1536.         // Media audio/video
  1537.         if ($bp['media'] != null) {
  1538.             echo " • <a href=\"" . $bp['media'] . "\">Download " . basename($bp['media']) . "</a>";
  1539.         }
  1540.  
  1541.         if (count($bp['tag']) > 0) {
  1542.             echo "<br />Tags: ";
  1543.             for ($i = 0; $i < count($bp['tag']); $i++) {
  1544.                 echo "<a href=\"?tag=" . $bp['tag'][$i] . "\">" . $bp['tag'][$i] . "</a>";
  1545.                 if ($i < count($bp['tag']) - 1)
  1546.                     echo ", ";
  1547.             }
  1548.         }
  1549.         echo "</div>";
  1550.  
  1551.         if($ext != 0 || $first != 0) {
  1552.             echo "<div class=\"imBlogPostBody\">";
  1553.  
  1554.             if ($bp['mediahtml'] != null) {
  1555.                 echo $bp['mediahtml'];
  1556.             }
  1557.  
  1558.             echo $bp['body'];
  1559.  
  1560.             if (count($bp['sources']) > 0) {
  1561.                 echo "<div class=\"imBlogSources\">";
  1562.                 echo "<b>" . $l10n['blog_sources'] . "</b>:<br />";
  1563.                 echo "<ul>";
  1564.  
  1565.                 foreach ($bp['sources'] as $source) {
  1566.                     echo "<li>" . $source . "</li>";
  1567.                 }
  1568.  
  1569.                 echo "</ul></div>";
  1570.             }
  1571.             echo (($imSettings['blog']['addThis'] != null) ? "<br />" . $imSettings['blog']['addThis'] : "") . "<br /><br /></div>";
  1572.         }
  1573.         else {
  1574.             echo "<div class=\"imBlogPostSummary\">" . $bp['summary'] . "</div>";
  1575.         }
  1576.         if($ext == 0) {
  1577.             echo "<div class=\"imBlogPostRead\"><a class=\"imCssLink\" href=\"?id=" . $id . "\">" . $l10n['blog_read_all'] ." »</a></div>";
  1578.         }
  1579.         else {
  1580.             echo "<div class=\"imBlogPostFooHTML\">" . $bp['foo_html'] . "</div>";
  1581.         }
  1582.  
  1583.         if($ext != 0 && $bp['comments'] == true) { //&& @chdir($imSettings['general']['dir'])
  1584.             echo "<div class=\"imBlogPostComments\">";
  1585.             if(($c = $this->getComments($id)) != -1) {
  1586.                 if(is_array($c))
  1587.                     foreach($c as $comment)
  1588.                         if($comment['approved'] == 1)
  1589.                             $ca[] = $comment;
  1590.                 echo "<div class=\"imBlogCommentsCount\">" . (count($ca) > 0 ? count($ca) . " " . (count($ca) > 1 ? $l10n['blog_comments'] : $l10n['blog_comment']) : $l10n['blog_no_comment']) . "</div>";
  1591.                 for($i = 0;$i < count($ca); $i++) {
  1592.                     echo "<div class=\"imBlogPostCommentUser\">" . (stristr($ca[$i]['url'],"http") ? "<a href=\"" . $ca[$i]['url'] . "\" target=\"_blank\">" . $ca[$i]['name'] . "</a>" : $ca[$i]['name']) . "</div>";
  1593.                     echo "<div class=\"imBlogPostCommentDate imBreadcrumb\" style=\"display: block\">" . $this->formatTimestamp($ca[$i]['timestamp']) . "</div>";
  1594.                     echo "<div class=\"imBlogPostCommentBody\">" . $ca[$i]['body'] . "</div>";
  1595.                     echo "<div class=\"imBlogPostAbuse\"><a href=\"" . basename($_SERVER['PHP_SELF']) . "?id=" . $id . "&abuse=" . ($i + 1) . "\"><img src=\"../res/exclamation.png\" alt=\"" . $l10n['blog_abuse'] . "\" title=\"" . $l10n['blog_abuse'] . "\" /></a></div>";
  1596.                 }
  1597.                 echo "<br />";
  1598.             }
  1599.             else {
  1600.                     echo "<div class=\"imBlogCommentsCount\">" . $l10n['blog_no_comment'] . "</div>";
  1601.             }
  1602.             if($_GET['ok'] == 1 && $imSettings['blog']['approve_comments']) {
  1603.                 echo "<div class=\"imBlogCommentsMsgOK\">" . $l10n['blog_send_confirmation'] . "<br /></div>";
  1604.             }
  1605.             if($_GET['err'] != "") {
  1606.                 echo "<div class=\"imBlogCommentsMsgErr\">" . $l10n['blog_send_error'] . "<br /></div>";
  1607.             }
  1608.             echo "<div class=\"imBlogCommentsForm\" style=\"width: 300px;\">
  1609.               <form id=\"blogComment\" action=\"" . $_SERVER['PHP_SELF'] . "?id=" . $id . "\" method=\"post\" onsubmit=\"return x5engine.imForm.validate(this, {type: 'tip', showAll: true})\">
  1610.                 <input type=\"hidden\" name=\"post_id\" value=\"" . $id . "\"/>
  1611.                 <div class=\"imBlogCommentRow\">
  1612.                     <label for=\"form_name\" style=\"float: left;\">" . $l10n['blog_name'] . "*</label> <input type=\"text\" id=\"form_name\" name=\"name\" class=\"imfield mandatory\" style=\"float: right;\" />
  1613.                 </div>
  1614.                 <div class=\"imBlogCommentRow\">
  1615.                     <label for=\"form_email\" style=\"float: left;\">" . $l10n['blog_email'] . "*</label> <input type=\"text\" id=\"form_email\" name=\"email\" class=\"imfield mandatory valEmail\" style=\"float: right;\" />
  1616.                 </div>
  1617.                 <div class=\"imBlogCommentRow\">
  1618.                     <label for=\"form_url\" style=\"float: left;\">" . $l10n['blog_website'] . "</label> <input type=\"text\" id=\"form_url\" name=\"url\" style=\"float: right;\" class=\"imfield\" />
  1619.                 </div>
  1620.                 <div class=\"imBlogCommentRow\">
  1621.                     <label for=\"form_body\" style=\"clear: both;\">" . $l10n['blog_message'] . "*</label><textarea id=\"form_body\" name=\"body\" class=\"imfield mandatory\" style=\"width: 100%; height: 100px;\"></textarea>
  1622.                 </div>";
  1623.                 if ($imSettings['blog']['captcha'])
  1624.                     echo "<div class=\"imBlogCommentRow\" style=\"text-align: center\">
  1625.                             <label for=\"imCpt\" style=\"float: left;\">" . $l10n['form_captcha_title'] . "</label> <input type=\"text\" id=\"imCpt\" name=\"imCpt\" class=\"imfield imCpt[5,../]\" size=\"5\" style=\"width: 120px; margin: 0 auto;\" />
  1626.                         </div>";
  1627.                 echo "<div class=\"imBlogCommentRow\" style=\"text-align: center; margin-bottom: 15px;\"><input type=\"submit\" value=\"" . $l10n['blog_send'] . "\" class=\"imBlogCommentSubmitBtn\"/></div>
  1628.               </form>
  1629.             </div>
  1630.             </div>";
  1631.         }
  1632.     }
  1633.  
  1634.     /**
  1635.      * Find the posts tagged with tag
  1636.      * @param tag The searched tag
  1637.      */
  1638.     function showTag($tag) {
  1639.         global $imSettings;
  1640.         if (count($imSettings['blog']['posts']) > 0) {
  1641.             $i = 0;
  1642.             foreach ($imSettings['blog']['posts'] as $id => $post) {
  1643.                 if (in_array($tag, $post['tag']))
  1644.                     echo $this->showPost($id,0,(($i == 0) ? 1 : 0));
  1645.                 if ($i > 0)
  1646.                     echo x5engine.imBlog.separator;
  1647.                 $i++;
  1648.             }
  1649.         }
  1650.         else {
  1651.             echo "<div class=\"imBlogEmpty\">Empty blog</div>";
  1652.         }
  1653.     }
  1654.  
  1655.     /**
  1656.      * Find the post in a category
  1657.      * @param category the category ID
  1658.      */
  1659.     function showCategory($category) {
  1660.         global $imSettings;
  1661.         $bps = $imSettings['blog']['posts_cat'][$category];
  1662.         if(is_array($bps)) {
  1663.             $bpsc = count($bps);
  1664.             for($i = 0; $i < $bpsc; $i++)
  1665.                 $this->showPost($bps[$i],0,($i == 0 ? 1 : 0));
  1666.         }
  1667.         else {
  1668.             echo "<div class=\"imBlogEmpty\">Empty category</div>";
  1669.         }
  1670.     }
  1671.  
  1672.     /**
  1673.      * Find the posts of the month
  1674.      * @param month
  1675.      */
  1676.     function showMonth($month) {
  1677.         global $imSettings;
  1678.         $bps = $imSettings['blog']['posts_month'][$month];
  1679.         if(is_array($bps)) {
  1680.             $bpsc = count($bps);
  1681.             for($i = 0; $i < $bpsc; $i++)
  1682.                 $this->showPost($bps[$i],0,($i == 0 ? 1 : 0));
  1683.         }
  1684.         else {
  1685.             echo "<div class=\"imBlogEmpty\">Empty month</div>";
  1686.         }
  1687.     }
  1688.  
  1689.     /**
  1690.      * Show the last n posts
  1691.      * @param count the number of posts to show
  1692.      */
  1693.     function showLast($count) {
  1694.         global $imSettings;
  1695.         $bps = array_keys($imSettings['blog']['posts']);
  1696.         if(is_array($bps)) {
  1697.             $bpsc = count($bps);
  1698.             for($i = 0; $i < ($bpsc<$count ? $bpsc : $count); $i++)
  1699.                 $this->showPost($bps[$i],0,($i == 0 ? 1 : 0));
  1700.         }
  1701.         else {
  1702.             echo "<div class=\"imBlogEmpty\">Empty blog</div>";
  1703.         }
  1704.     }
  1705.  
  1706.     /**
  1707.      * Show the search results
  1708.      * @param search the search query
  1709.      */
  1710.     function showSearch($search) {
  1711.         global $imSettings;
  1712.         $bps = array_keys($imSettings['blog']['posts']);
  1713.         $j = 0;
  1714.         if(is_array($bps)) {
  1715.             $bpsc = count($bps);
  1716.             for($i = 0; $i < $bpsc; $i++) {
  1717.                 if(stristr($imSettings['blog']['posts'][$bps[$i]]['title'],$search) || stristr($imSettings['blog']['posts'][$bps[$i]]['summary'],$search) || stristr($imSettings['blog']['posts'][$bps[$i]]['body'],$search)) {
  1718.                     $this->showPost($bps[$i],0,($j == 0 ? 1 : 0));
  1719.                     $j++;
  1720.                 }
  1721.             }
  1722.             if($j == 0) {
  1723.                 echo "<div class=\"imBlogEmpty\">Empty search</div>";
  1724.             }
  1725.         }
  1726.         else {
  1727.             echo "<div class=\"imBlogEmpty\">Empty blog</div>";
  1728.         }
  1729.     }
  1730.  
  1731.     /**
  1732.      * Show the categories sideblock
  1733.      * @param n The number of categories to show
  1734.      */
  1735.     function showBlockCategories($n) {
  1736.         global $imSettings;
  1737.  
  1738.         if (is_array($imSettings['blog']['posts_cat'])) {
  1739.             $categories = array_keys($imSettings['blog']['posts_cat']);
  1740.             array_multisort($categories);
  1741.             echo "<ul>";
  1742.             for ($i = 0; $i < count($categories) && $i < $n; $i++) {
  1743.                 $post = $imSettings['blog']['posts'][$imSettings['blog']['posts_cat'][$categories[$i]][0]];
  1744.                 echo "<li><a href=\"?category=" . $categories[$i] . "\">" . $post['category'] . "</a></li>";
  1745.             }
  1746.             echo "</ul>";
  1747.         }
  1748.     }
  1749.  
  1750.     /**
  1751.      * Show the cloud sideblock
  1752.      * @param type TAGS or CATEGORY
  1753.      */
  1754.     function showBlockCloud($type) {
  1755.         global $imSettings;
  1756.  
  1757.         $max = 0;
  1758.         if ($type == "tags") {
  1759.             $tags = array();
  1760.             foreach ($imSettings['blog']['posts'] as $id => $post) {
  1761.                 foreach ($post['tag'] as $tag) {
  1762.                     if ($tags[$tag] == null)
  1763.                         $tags[$tag] = 1;
  1764.                     else
  1765.                         $tags[$tag] = $tags[$tag] + 1;
  1766.                     if ($tags[$tag] > $max)
  1767.                         $max = $tags[$tag];
  1768.                 }
  1769.             }
  1770.  
  1771.             $tags = shuffle_assoc($tags);
  1772.  
  1773.             $min_em = 0.7;
  1774.             $max_em = 1.3;
  1775.             foreach ($tags as $name => $number) {
  1776.                 $size = number_format(($number/$max * ($max_em - $min_em)) + $min_em, 2, '.', '');
  1777.                 echo "<span class=\"imBlogCloudItem\" style=\"font-size: " . $size . "em;\"><a href=\"?tag=" . $name . "\">" . $name . "</a></span>\n";
  1778.             }
  1779.         } else if ($type == "categories") {
  1780.             $categories = array();
  1781.             foreach ($imSettings['blog']['posts'] as $id => $post) {
  1782.                 if ($categories[$post['category']] == null)
  1783.                     $categories[$post['category']] = 1;
  1784.                 else
  1785.                     $categories[$post['category']] = $categories[$post['category']] + 1;
  1786.                 if ($categories[$post['category']] > $max)
  1787.                     $max = $categories[$post['category']];
  1788.             }
  1789.  
  1790.             $categories[$category] = shuffle_assoc($categories[$category]);
  1791.  
  1792.             $min_em = 0.7;
  1793.             $max_em = 1.3;
  1794.             foreach ($categories as $name => $number) {
  1795.                 $size = number_format(($number/$max * ($max_em - $min_em)) + $min_em, 2, '.', '');
  1796.                 echo "<span class=\"imBlogCloudItem\" style=\"font-size: " . $size . "em;\"><a href=\"?category=" . str_replace(" ", "_", $name) . "\">" . $name . "</a></span>\n";
  1797.             }
  1798.         }
  1799.     }
  1800.  
  1801.     /**
  1802.      * Show the month sideblock
  1803.      * @param n Number of entries
  1804.      */
  1805.     function showBlockMonths($n) {
  1806.         global $imSettings;
  1807.  
  1808.         if (is_array($imSettings['blog']['posts_month'])) {
  1809.             $months = array_keys($imSettings['blog']['posts_month']);
  1810.             array_multisort($months);
  1811.             echo "<ul>";
  1812.             for ($i = 0; $i < count($months) && $i < $n; $i++) {
  1813.                 $post = $imSettings['blog']['posts'][$imSettings['blog']['posts_cat'][$categories[$i]][0]];
  1814.                 echo "<li><a href=\"?month=" . $months[$i] . "\">" . substr($months[$i], 4) . "/" . substr($months[$i], 0, 4) . "</a></li>";
  1815.             }
  1816.             echo "</ul>";
  1817.         }
  1818.     }
  1819.  
  1820.     /**
  1821.      * Show the last posts block
  1822.      * @param n The number of post to show
  1823.      */
  1824.     function showBlockLast($n) {
  1825.         global $imSettings;
  1826.  
  1827.         if (is_array($imSettings['blog']['posts'])) {
  1828.             echo "<ul>";
  1829.             for ($i = 0; $i < count($imSettings['blog']['posts']) && $i < $n; $i++) {
  1830.                 $post = array_keys($imSettings['blog']['posts']);
  1831.                 $post = $imSettings['blog']['posts'][$post[$i]];
  1832.                 echo "<li><a href=\"?id=" . $post['id'] . "\">" . $post['title'] . "</a></li>";
  1833.             }
  1834.             echo "</ul>";
  1835.         }
  1836.     }
  1837. }
  1838.  
  1839. /**
  1840.  * Guestbook class
  1841.  * @access public
  1842.  */
  1843. class imGuestBook {
  1844.     var $comments;
  1845.     var $path;
  1846.     var $email;
  1847.     var $direct_approval;
  1848.  
  1849.     // PHP 5
  1850.     function __construct($path, $email = '', $direct_approval = TRUE) {
  1851.         if ($direct_approval == TRUE)
  1852.             $this->direct_approval = 1;
  1853.         else
  1854.             $this->direct_approval = 0;
  1855.         if ($email != "" && $email != null)
  1856.             $this->email = $email;
  1857.         $this->comments = new imComment();
  1858.         if (substr($path, -1, 1) != "/" && $path != "")
  1859.             $path .= "/";
  1860.         if ($path != null)
  1861.             $this->path = $path;
  1862.         else
  1863.             $this->path = $imSettings['general']['dir'];
  1864.             
  1865.         if (!file_exists($this->path) && $this->path != "" && $this->path != "./.") {
  1866.             mkdir($this->path, 0777, TRUE);
  1867.         }
  1868.     }
  1869.  
  1870.     // PHP 4
  1871.     function imGuestBook($path, $email = '', $direct_approval = TRUE) {
  1872.         if ($direct_approval == TRUE)
  1873.             $this->direct_approval = 1;
  1874.         else
  1875.             $this->direct_approval = 0;
  1876.         if ($email != "" && $email != null)
  1877.             $this->email = $email;
  1878.         $this->comments = new imComment();
  1879.         if (substr($path, -1, 1) != "/" && $path != "")
  1880.             $path .= "/";
  1881.         if ($path != null)
  1882.             $this->path = $path;
  1883.         else
  1884.             $this->path = $imSettings['general']['dir'];
  1885.             
  1886.         if (!file_exists($this->path) && $this->path != "" && $this->path != "./.") {
  1887.             mkdir($this->path, 0777, TRUE);
  1888.         }
  1889.     }
  1890.  
  1891.     function formatTimestamp($ts) {
  1892.         return date("d/m/Y H:i:s", strtotime($ts));
  1893.     }
  1894.  
  1895.     /**
  1896.      * Get the comments of the guestbook ID
  1897.      * @param id The guestbook ID
  1898.      */
  1899.     function getComments($id) {
  1900.         global $imSettings;
  1901.         return $this->comments->getComments($this->path . "gb" . $id);
  1902.     }
  1903.  
  1904.     /**
  1905.      * Add a comment
  1906.      * @param id The guestbook ID
  1907.      * @param name The user's name
  1908.      * @param email The user's email
  1909.      * @param url The user's site url
  1910.      * @param body The user's message
  1911.      */
  1912.     function addComment($id,$name,$email,$url,$body) {
  1913.         global $imSettings;
  1914.         $em = new imSendEmail();
  1915.         $em->sendGuestbookEmail($id, $name, $email, $url, $body, $this->direct_approval, $this->email);
  1916.         return $this->comments->addComment($this->path . "gb" . $id,$name,$email,$url,$body, "0", $this->direct_approval);
  1917.     }
  1918.  
  1919.     /**
  1920.      * Approve a comment
  1921.      * @param id the guestbook ID
  1922.      * @param n The comment number
  1923.      * @param approved Set 1 to approve
  1924.      */
  1925.     function approveComment($id,$n,$approved) {
  1926.         global $imSettings;
  1927.         return $this->comments->approveComment($this->path . "gb" . $id,$n,$approved);
  1928.     }
  1929.  
  1930.     /**
  1931.      * Delete a comment
  1932.      * @param id the guestbook ID
  1933.      * @param n The comment number
  1934.      */
  1935.     function removeComment($id,$n) {
  1936.         global $imSettings;
  1937.         return $this->comments->removeComment($this->path . "gb" . $id, $n);
  1938.     }
  1939.  
  1940.     /**
  1941.      * Abuse a comment
  1942.      * @param post the post ID
  1943.      * @param n The comment number
  1944.      * @param abuse Set 1 to abuse
  1945.      */
  1946.     function setAbuse($id, $n, $abuse) {
  1947.         global $imSettings;
  1948.         return $this->comments->setAbuse($this->path . "gb" . $id, $n, $abuse);
  1949.     }
  1950.  
  1951.     /**
  1952.      * Show a guestbook
  1953.      * @param id the guestbook ID
  1954.      * @param captcha Set TRUE to show
  1955.      */
  1956.     function showGuestBook($id, $captcha = TRUE) {
  1957.         global $imSettings;
  1958.         global $l10n;
  1959.         echo "<div class=\"imBlogPostComments\">";
  1960.         if(($c = $this->getComments($id)) != -1) {
  1961.             if(is_array($c))
  1962.                 foreach($c as $comment)
  1963.                     if($comment['approved'] == 1)
  1964.                         $ca[] = $comment;
  1965.             echo "<div class=\"imBlogCommentsCount\">" . (count($ca) > 0 ? count($ca) . " " . (count($ca) > 1 ? $l10n['blog_comments'] : $l10n['blog_comment']) : $l10n['blog_no_comment']) . "</div>";
  1966.             for($i = 0;$i < count($ca); $i++) {
  1967.                 echo "<div class=\"imBlogPostCommentUser\">" . (stristr($ca[$i]['url'],"http") ? "<a href=\"" . $ca[$i]['url'] . "\" target=\"_blank\">" . $ca[$i]['name'] . "</a>" : $ca[$i]['name']) . "</div>";
  1968.                 echo "<div class=\"imBlogPostCommentDate imBreadcrumb\" style=\"display: block;\">" . $this->formatTimestamp($ca[$i]['timestamp']) . "</div>";
  1969.                 echo "<div class=\"imBlogPostCommentBody\">" . $ca[$i]['body'] . "</div>";
  1970.                 echo "<div class=\"imBlogPostAbuse\"><a href=\"" . basename($_SERVER['PHP_SELF']) . "?id=" . $id . "&abuse=" . ($i + 1) . "\"><img src=\"res/exclamation.png\" alt=\"" . $l10n['blog_abuse'] . "\" title=\"" . $l10n['blog_abuse'] . "\" /></a></div>";
  1971.             }
  1972.         }
  1973.         else {
  1974.             echo "<div class=\"imGuestbookCount\">" . $l10n['blog_no_comment'] . "</div>";
  1975.         }
  1976.         if($_GET['ok_' . $id] == 1 && $this->direct_approval == 0) {
  1977.             echo "<div class=\"imGuestbookMsgOK\">" . $l10n['blog_send_confirmation'] . "</div><br /><br />";
  1978.         }
  1979.         if($_GET['err_' . $id] != "") {
  1980.             echo "<div class=\"imGuestbookErr\">" . $l10n['blog_send_error'] . "</div><br /><br />";
  1981.         }
  1982.  
  1983.         echo "<div class=\"imBlogCommentsForm\">
  1984.               <form id=\"guestBookComment_" . $id . "\" action=\"" . $_SERVER['PHP_SELF'] . "?id=" . $id . "\" method=\"post\" onsubmit=\"return x5engine.imForm.validate(this, {type: 'tip', showAll: true})\">
  1985.                 <input type=\"hidden\" name=\"post_id\" value=\"" . $id . "\"/>
  1986.                 <div class=\"imBlogCommentRow\">
  1987.                     <label for=\"form_name\" style=\"float: left; width: 100px;\">" . $l10n['blog_name'] . "*</label> <input type=\"text\" id=\"form_name\" name=\"name\" class=\"imfield mandatory\" />
  1988.                 </div>
  1989.                 <div class=\"imBlogCommentRow\">
  1990.                     <label for=\"form_email\" style=\"float: left; width: 100px;\">" . $l10n['blog_email'] . "*</label> <input type=\"text\" id=\"form_email\" name=\"email\" class=\"imfield mandatory valEmail\"/>
  1991.                 </div>
  1992.                 <div class=\"imBlogCommentRow\">
  1993.                     <label for=\"form_url\" style=\"float: left; width: 100px;\">" . $l10n['blog_website'] . "</label> <input type=\"text\" id=\"form_url\" name=\"url\" class=\"imfield\" />
  1994.                 </div>
  1995.                 <div class=\"imBlogCommentRow\">
  1996.                     <br /><label for=\"form_body\" style=\"clear: both; width: 100px;\">" . $l10n['blog_message'] . "*</label><textarea id=\"form_body\" name=\"body\" class=\"imfield mandatory\" style=\"width: 95%; height: 100px;\"></textarea>
  1997.                 </div>";
  1998.                 if ($captcha)
  1999.                     echo "<div class=\"imBlogCommentRow\" style=\"text-align: center\">
  2000.                             <label for=\"imGuestBookCpt" . $id . "_imCpt\" style=\"float: left;\">" . $l10n['form_captcha_title'] . "</label> <input type=\"text\" id=\"imGuestBookCpt" . $id . "_imCpt\" name=\"imCpt\" maxlength=\"5\" class=\"imfield imCpt[5]\" size=\"5\" style=\"width: 120px; margin: 0 auto;\" />
  2001.                         </div>";
  2002.                 echo "<div class=\"imBlogCommentRow\" style=\"text-align: center\">
  2003.                         <input type=\"submit\" value=\"" . $l10n['form_submit'] . "\" />
  2004.                         <input type=\"reset\" value=\"" . $l10n['form_reset'] . "\" />
  2005.                     </div>
  2006.               </form>
  2007.               <script type=\"text/javascript\">x5engine.imForm.initForm('#guestBookComment_" . $id . "');</script>
  2008.             </div>
  2009.             </div>";
  2010.     }
  2011. }
  2012.  
  2013. /**
  2014.  * Star rating class
  2015.  * @access public
  2016.  */
  2017. class imStarRating {
  2018.  
  2019.     var $id;
  2020.     var $scale;
  2021.  
  2022.     // PHP 5
  2023.     function __construct($id, $scale) {
  2024.         $this->id = $id;
  2025.         $this->scale = $scale;
  2026.     }
  2027.  
  2028.     // PHP 4
  2029.     function imStarRating($id, $scale) {
  2030.         $this->id = $id;
  2031.         $this->scale = $scale;
  2032.     }
  2033.  
  2034.     /**
  2035.      * Get the rating from a file
  2036.      */
  2037.     function getRating() {
  2038.         global $imSettings;
  2039.         $xml = new imXML();
  2040.         $rating = $xml->parse_file($imSettings['general']['dir'] . "/" . $imSettings['guestbook']['file_prefix'] . "sr" . $this->id);
  2041.         if ($rating['scale'] == "" || $rating['scale'] == null)
  2042.             $rating['scale'] = $this->scale;
  2043.         if (is_array($rating))
  2044.             return $rating;
  2045.         else
  2046.             return FALSE;
  2047.     }
  2048.  
  2049.     /**
  2050.      * Set a rating
  2051.      * @param value The rating value
  2052.      * @param scale The rating maximum value
  2053.      */
  2054.     function setRating($value, $scale) {
  2055.         global $imSettings;
  2056.         $rating = $this->getRating();
  2057.         if (!$rating)
  2058.             $rating = array('scale' => $scale, 'vote_sum' => 0, 'count' => 0);
  2059.         $rating['vote_sum'] += $value;
  2060.         $rating['count'] += 1;
  2061.  
  2062.         $fp = fopen($imSettings['general']['dir'] . "/" . $imSettings['guestbook']['file_prefix'] . "sr" . $this->id, "w");
  2063.         if (!$fp)
  2064.             return FALSE;
  2065.  
  2066.         $xml =  "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  2067.         $xml .= "<rating>\n";
  2068.         $xml .= "\t<count>" . $rating['count'] . "</count>\n";
  2069.         $xml .= "\t<vote_sum>" . $rating['vote_sum'] . "</vote_sum>\n";
  2070.         $xml .= "\t<scale>" . $rating['scale'] . "</scale>\n";
  2071.         $xml .= "</rating>";
  2072.  
  2073.         fwrite($fp, $xml);
  2074.         fclose($fp);
  2075.  
  2076.         return TRUE;
  2077.     }
  2078.  
  2079.     /**
  2080.      * Show the rating widget
  2081.      */
  2082.     function showWidget() {
  2083.         $html =  "<div class=\"imStarRating\">\n";
  2084.         $avg_vote = 0;
  2085.         if (@$_COOKIE[$this->id] != "y" && @$_POST['id'] != "" && @$_POST['scale'] != "" && @$_POST['value'] != "" && @$_POST['id'] == $this->id) {
  2086.             $this->setRating(@$_POST['value'], @$_POST['scale']);
  2087.         }
  2088.         $rating = $this->getRating();
  2089.         if ($rating['count'] > 0)
  2090.             $avg_vote = round($rating['vote_sum'] / $rating['count'], 1);
  2091.         $html .= "Vote: " . $avg_vote . "/" . $this->scale . "<br />";
  2092.         if (@$_COOKIE[$this->id] != "y") {
  2093.             for ($i = 0; $i < $rating['scale']; $i++)
  2094.                 $html .= "<img src=\"res/star_empty.png\" style=\"cursor: pointer;\" id=\"" . $this->id . "_star" . ($i + 1) . "\" class=\"imStarRating[" . ($i + 1) . "]\" />";
  2095.             $html .= "<script type=\"text/javascript\">x5engine.imQueue.push_init(\"x5engine.imStarRating('" . $this->id . "', " . $rating['scale'] . ", '" . basename($_SERVER['PHP_SELF']) . "')\");</script>\n";
  2096.         }
  2097.         $html .= "</div>\n";
  2098.  
  2099.         echo $html;
  2100.     }
  2101. }
  2102.  
  2103. /**
  2104.  * Server Test Class
  2105.  * @access public
  2106.  */
  2107. class imTest {
  2108.     
  2109.     /*
  2110.      * Session check
  2111.      */
  2112.     function session_test() {
  2113.         global $l10n;
  2114.         if (!isset($_SESSION))
  2115.             return array(FALSE, null);
  2116.         $_SESSION['imAdmin_test'] = "test_message";
  2117.         if ($_SESSION['imAdmin_test'] != "test_message")
  2118.             return array(FALSE, $l10n['admin_test_session_suggestion']);
  2119.         return array(TRUE);
  2120.     }
  2121.  
  2122.     /*
  2123.      * Writable files check
  2124.      */
  2125.     function writable_folder_test() {
  2126.         global $imSettings;
  2127.         global $l10n;
  2128.         
  2129.         $root = getcwd();
  2130.         $dir = $imSettings['general']['dir'];
  2131.         
  2132.         if (!file_exists($imSettings['general']['dir']) && $imSettings['general']['dir'] != "" && $imSettings['general']['dir'] != "./.")
  2133.             @mkdir($imSettings['general']['dir'], 0777, TRUE);
  2134.  
  2135.         if ($dir != "" && !@chdir($dir)) {
  2136.             @chdir($root);
  2137.             return array(FALSE, $l10n['admin_test_folder_suggestion']);
  2138.         }
  2139.  
  2140.         $fp = @fopen("imAdmin_test_file", "w");
  2141.         if (!$fp) {
  2142.             @chdir($root);
  2143.             return array(FALSE, $l10n['admin_test_folder_suggestion']);
  2144.         }
  2145.         if (fwrite($fp, "test") === FALSE) {
  2146.             @chdir($root);
  2147.             return array(FALSE, $l10n['admin_test_folder_suggestion']);
  2148.         }
  2149.         fclose($fp);
  2150.         if (file_exists("imAdmin_test_file")) {
  2151.             unlink("imAdmin_test_file");
  2152.             @chdir($root);
  2153.             return array(TRUE);
  2154.         }
  2155.         @chdir($root);
  2156.         return array(FALSE, $l10n['admin_test_folder_suggestion']);
  2157.     }
  2158.  
  2159.     /*
  2160.      * PHP Version check
  2161.      */
  2162.     function php_version_test() {
  2163.         global $l10n;
  2164.         $php_version = PHP_VERSION;
  2165.         if (version_compare($php_version, '4.0.0') < 0)
  2166.             return array(FALSE, $l10n['admin_test_version_suggestion']);
  2167.  
  2168.         return array(TRUE, $l10n['admin_test_version_suggestion']);
  2169.     }
  2170.  
  2171.     /*
  2172.      * MySQL Connection check
  2173.      */
  2174.     function mysql_test() {
  2175.         global $imSettings;
  2176.         global $l10n;
  2177.         $r = TRUE;
  2178.         $dir = "mail";
  2179.         if (is_dir($dir)) {
  2180.             if ($dh = opendir($dir)) {
  2181.                 while (($file = readdir($dh)) !== FALSE) {
  2182.                     if ($file != ".." && $file != ".")
  2183.                         include($dir . "/" . $file);
  2184.                 }
  2185.                 closedir($dh);
  2186.             }
  2187.         }
  2188.         
  2189.         if (is_array($settings)) {
  2190.             foreach ($settings as $form) {
  2191.                 if ($form['db_host'] != NULL) {
  2192.                     $test = new imDatabase($form['db_host'], $form['db_name'], $form['db_username'], $form['db_password'], "", "");
  2193.                     if ($test->test_connection() === FALSE)
  2194.                         $r = FALSE;
  2195.                 }
  2196.             }
  2197.         }
  2198.  
  2199.         return array($r, $l10n['admin_test_database_suggestion']);
  2200.     }
  2201.  
  2202.     /*
  2203.      * Do the test
  2204.      */
  2205.     function doTest($name, $funct) {
  2206.         $result = $this->$funct();
  2207.         if ($result[0])
  2208.             echo "<div class=\"imTest pass\">" . $name . "<span>PASS</span></div>";
  2209.         else
  2210.             echo "<div class=\"imTest fail\">" . $name . "<span>FAIL</span><br /><img src=\"../res/info.gif\"/ style=\"vertical-align: middle;\"> " . $result[1] . "</div>";
  2211.     }
  2212. }
  2213.  
  2214. /**
  2215.  * Google Webmaster Tools Class
  2216.  * @access public
  2217.  */
  2218. class imGoogle {
  2219.  
  2220.     var $auth;
  2221.     var $err = false;
  2222.  
  2223.     // PHP 5
  2224.     function __construct($uname, $pwd, $service) {
  2225.         global $phpError;
  2226.         $curl = curl_init();
  2227.         if (curl_setopt($curl, CURLOPT_URL, "https://www.google.com/accounts/ClientLogin") && !$phpError) {
  2228.             curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  2229.             curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
  2230.             curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
  2231.             curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
  2232.             curl_setopt($curl, CURLOPT_POST, true);
  2233.             $post = array(
  2234.                 'accountType' => 'HOSTED_OR_GOOGLE',
  2235.                 'Email' => $uname,
  2236.                 'Passwd' => $pwd,
  2237.                 'service' => $service,
  2238.                 'source' => ''
  2239.             );
  2240.             curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
  2241.             $output = curl_exec($curl);
  2242.             $info = curl_getinfo($curl);
  2243.             curl_close($curl);
  2244.             if($info['http_code'] == 200) {
  2245.                 preg_match('/Auth=(.*)/', $output, $match);
  2246.                 if(isset($match[1]))
  2247.                     $this->auth = $match[1];
  2248.                 else
  2249.                     $this->auth = FALSE;
  2250.             }
  2251.         } else {
  2252.             $this->err = TRUE;
  2253.             return FALSE;
  2254.         }
  2255.     }
  2256.  
  2257.     // PHP 4
  2258.     function imGoogle($uname, $pwd, $service) {
  2259.         global $phpError;
  2260.         $curl = curl_init();
  2261.         if (curl_setopt($curl, CURLOPT_URL, "https://www.google.com/accounts/ClientLogin") && !$phpError) {
  2262.             curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  2263.             curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
  2264.             curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
  2265.             curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
  2266.             curl_setopt($curl, CURLOPT_POST, true);
  2267.             $post = array(
  2268.                 'accountType' => 'HOSTED_OR_GOOGLE',
  2269.                 'Email' => $uname,
  2270.                 'Passwd' => $pwd,
  2271.                 'service' => $service,
  2272.                 'source' => ''
  2273.             );
  2274.             curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
  2275.             $output = curl_exec($curl);
  2276.             $info = curl_getinfo($curl);
  2277.             curl_close($curl);
  2278.             if($info['http_code'] == 200) {
  2279.                 preg_match('/Auth=(.*)/', $output, $match);
  2280.                 if(isset($match[1]))
  2281.                     $this->auth = $match[1];
  2282.                 else
  2283.                     $this->auth = FALSE;
  2284.             }
  2285.         } else {
  2286.             $this->err = TRUE;
  2287.             return FALSE;
  2288.         }
  2289.     }
  2290.  
  2291.     function urlencoding($site) {
  2292.         return str_replace(".", "%2E", urlencode($site));
  2293.     }
  2294.  
  2295.     /**
  2296.      * Get an array with the data results from Google
  2297.      * @param site The site url
  2298.      * @param operation the operation id
  2299.      */
  2300.     function readServiceData($site, $operation) {
  2301.         if ($this->auth === FALSE)
  2302.             return FALSE;
  2303.  
  2304.         if(strlen($site)>0)$request = $this->urlencoding($site) . "/" . $operation . "/";
  2305.         else $request = $operation."/";
  2306.         $url = "https://www.google.com/webmasters/tools/feeds/" . $request;
  2307.         $curl = curl_init();
  2308.         $head = array("Authorization: GoogleLogin auth=" . $this->auth,"GData-Version: 2");
  2309.         curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  2310.         curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
  2311.         curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
  2312.         curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
  2313.         curl_setopt($curl, CURLOPT_URL, $url);
  2314.         curl_setopt($curl, CURLOPT_HTTPHEADER, $head);
  2315.         $result = curl_exec($curl);
  2316.         $info = curl_getinfo($curl);
  2317.         curl_close($curl);
  2318.         if ($info['http_code']!=200)
  2319.             return FALSE;
  2320.  
  2321.         $xml = new imXML();
  2322.         $xml_output = $xml->parse_string($result);
  2323.  
  2324.         return $xml_output;
  2325.     }
  2326.  
  2327.     function getKeywords($site) {
  2328.         return $this->readServiceData($site, "keywords");
  2329.     }
  2330.  
  2331.     function getSitemap($site) {
  2332.         return $this->readServiceData($site, "sitemaps");
  2333.     }
  2334.  
  2335.     function getMessages($site) {
  2336.         return $this->readServiceData($site, "messages");
  2337.     }
  2338.  
  2339.     function getCrawler($site) {
  2340.         return $this->readServiceData($site, "crawlissues");
  2341.     }
  2342. }
  2343.  
  2344. /**
  2345. * Set the error handler
  2346. */
  2347.  
  2348. function imErrorHandler($errno, $errstr, $errfile, $errline)
  2349. {
  2350.     global $phpError;
  2351.     $phpError = true;
  2352.     return true;
  2353. }
  2354.  
  2355. set_error_handler("imErrorHandler");
  2356.  
  2357. /**
  2358.  * Useful functions
  2359.  */
  2360.  
  2361. function filterCode($str) {
  2362.     while (($start = strpos($str, "<script")) !== FALSE) {
  2363.         $end = strpos($str, "</script>") + strlen("</script>");
  2364.         $str = substr($str, 0, $start) . substr($str, $end);
  2365.     }
  2366.     
  2367.     while (($start = strpos($str, "<?")) !== FALSE) {
  2368.         $end = strpos($str, "?>") + strlen("?>");
  2369.         $str = substr($str, 0, $start) . substr($str, $end);
  2370.     }
  2371.     
  2372.     while (($start = strpos($str, "<%")) !== FALSE) {
  2373.         $end = strpos($str, "%>") + strlen("<%");
  2374.         $str = substr($str, 0, $start) . substr($str, $end);
  2375.     }
  2376.     
  2377.     $str = strip_tags($str, '<b><i><u>');
  2378.     
  2379.     $count = 1;
  2380.     while ($count) $str = preg_replace("/(<[\\s\\S]+) on.*\\=(['\"\"])[\\s\\S]+\\2/i", "\\1", $str, -1, $count);
  2381.         
  2382.     return $str;
  2383. }
  2384.  
  2385. function imPrintJsError() {
  2386.     global $l10n;
  2387.     $html = "<DOCTYPE><html><head><meta http-equiv=\"Refresh\" content=\"5;URL=" . $_SERVER['HTTP_REFERER'] . "\"></head><body>";
  2388.     $html .= $l10n['form_js_error'];
  2389.     $html .= "</body></html>";
  2390.     return $html;
  2391. }
  2392.  
  2393. function imCheckAccess($page) {
  2394.     $pa = new imPrivateArea();
  2395.     $stat = $pa->checkAccess($page);
  2396.     if ($stat == -1) {
  2397.         $pa->save_page();
  2398.         header("Location: imlogin.php");
  2399.     } else if ($stat == -2) {
  2400.         $pa->save_page();
  2401.         header("Location: imlogin.php?err=1");
  2402.     }
  2403. }
  2404.  
  2405. function showGuestBook($id, $path, $email, $captcha = TRUE, $direct_approval = TRUE) {
  2406.     $gb = new imGuestBook($path, $email, $direct_approval);
  2407.  
  2408.     if (isset($_GET['abuse']))
  2409.         $gb->setAbuse($id, $_GET['abuse'], 1);
  2410.  
  2411.     if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['body']) && isset($_POST['post_id']) && $_POST['post_id'] == $id) {
  2412.         $result = $gb->addComment($id,$_POST['name'],$_POST['email'],$_POST['url'],$_POST['body']);
  2413.         if ($result === 0)
  2414.             echo "<script type=\"text/javascript\">location.href='" . $_SERVER['PHP_SELF'] . "?ok_" . $id . "=1';</script>";
  2415.         else
  2416.             echo "<script type=\"text/javascript\">location.href='" . $_SERVER['PHP_SELF'] . "?err_" . $id . "=" . $result . "';</script>";
  2417.     } else
  2418.         $gb->showGuestBook($id, $captcha);
  2419. }
  2420.  
  2421. function showStarRating($id) {
  2422.     $rating = new imStarRating($id, 5);
  2423.     $rating->showWidget();
  2424. }
  2425.  
  2426. function imCurrency($amount,$from,$to) {
  2427.     $amount = urlencode($amount);
  2428.     $from = urlencode($from);
  2429.     $to = urlencode($to);
  2430.     $url = "http://www.google.com/ig/calculator?hl=en&q=" . $amount . $from . "=?" . $to;
  2431.     $curl = curl_init();
  2432.     $timeout = 0;
  2433.     curl_setopt ($curl, CURLOPT_URL, $url);
  2434.     curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
  2435.     curl_setopt ($curl,  CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
  2436.     curl_setopt ($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
  2437.     $rawdata = curl_exec($curl);
  2438.     curl_close($curl);
  2439.     $data = explode('"', $rawdata);
  2440.     $data = explode(' ', $data['3']);
  2441.     $var = $data['0'];
  2442.     return "{ \"value\": " . $var . "}";
  2443. }
  2444.  
  2445. function imValidateVAT($vat, $country) {
  2446.     $url = "http://isvat.appspot.com/" . $country . "/" . $vat . "/?callback=?";
  2447.     $curl = curl_init();
  2448.     $timeout = 0;
  2449.     curl_setopt ($curl, CURLOPT_URL, $url);
  2450.     curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
  2451.     curl_setopt ($curl,  CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
  2452.     curl_setopt ($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
  2453.     return curl_exec($curl);
  2454. }
  2455.  
  2456. function shuffle_assoc($list) {
  2457.   if (!is_array($list)) return $list;
  2458.  
  2459.   $keys = array_keys($list);
  2460.   shuffle($keys);
  2461.   $random = array();
  2462.   foreach ($keys as $key)
  2463.     $random[$key] = $list[$key];
  2464.  
  2465.   return $random;
  2466. }
  2467.  
  2468. // End of file x5engine.php